tags:

views:

208

answers:

1

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

Here is my implementation which is failing:

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 any alternate methods. Please guide me on this. Thanks

+1  A: 

When the interface method is throwing an exception too, you should remove the catch blocks without

try {
                //....

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

And than your exception handling should work.

EDIT:

Do you have implemented the interface methods of ServletContextListener correctly? They are not in your code example. But they have to be in the class.

As far as i see, the interfae methods are not throwing any type of exceptions. When you realy want to BREAK the listener notification, you have to throw a RuntimeException.

EDIT2:

I would also change

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

to

if(!"aasditya".equals(str)){
throw new ServletException();
}
Markus Lausberg
"Do you have implemented the interface methods of ServletContextListener correctly? They are not in your code example. But they have to be in the class." - Yes I have added them .I'm calling the above method from in interface-method.
Aditya R