Throwing an exception from a ServletContextListener

I want to throw a ServletContext exception from a method in a class that implements ServletContextLister .

Here is my unsuccessful implementation:

 public class Initializer implements ServletContextListener { private void checkEncryptedFile() throws ServletException { FileReader fr; try { fr = new FileReader("TestFile"); BufferedReader br = new BufferedReader(fr); String str = br.readLine(); if(!str.equals("aasditya")){ throw new ServletException(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } catch(ServletException se){ throw new ServletException("kiasku " + se.getMessage(), se); } } } 

Can anyone suggest alternative methods. Please help me with this. Thanks

+4
source share
1 answer

When the interface method also throws an exception, you must remove the catch blocks without

 try { //.... } catch(IOException e){ throw new ServletException("kiasku " + e.getMessage(), e); } 

And how your exception handling should work.

EDIT:

Did you apply the ServletContextListener interface methods correctly? They are not in your sample code. But they must be in class.

As far as I can see, interfae methods do not throw any exceptions. When you really want to BREAK notify the listener, you need to throw a RuntimeException.

EDIT2:

I would change too

 if(!str.equals("aasditya")){ throw new ServletException(); } 

to

 if(!"aasditya".equals(str)){ throw new ServletException(); } 
+2
source

All Articles