How to throw exceptions for init () method for servlets

Ok, I will show my code first:

@Override
public void init() throws ServletException {
    super.init();

    try {
        securityController = SecurityControllerFactory.getInstance().create();
    } catch (Exception e) {
        System.err.println("Error creating security controller; " + e.getMessage());
    }

    // max allowed uploaded uploadedFile size is 10 MB
    maxFileSize = getBytes(10);
    maxMemSize = getBytes(2);
}

As you can see, the compiler forces me to use try / catch to instantiate the SecurityController. In my case, however, I believe that it should stop creating the Servlet instance and generally throw an exception if the security controller cannot be created. Any suggestions / clarifications to this?

+5
source share
3 answers

Read the javadoc methodinit() carefully :

Init

public void init() throws ServletException

...

Throws:

ServletException - if an exception occurs that interrupts the normal operation of the servlet

, ServletException. 2.3.2.1 API- :

2.3.2.1

UnavailableException ServletException. . destroy , .

...

, , ( , , Java /, ):

@Override
public void init() throws ServletException {
    try {
        securityController = SecurityControllerFactory.getInstance().create();
    } catch (Exception e) {
        throw new ServletException("Error creating security controller", e);
    }

    maxFileSize = getBytes(10);
    maxMemSize = getBytes(2);
}

, super.init(). Javadoc , init(), init(ServletConfig).


, catch Exception . , , RuntimeException catch Exception, / .

catch, (), throws . :

    try {
        securityController = SecurityControllerFactory.getInstance().create();
    } catch (SecurityControllerCreationException e) {
        throw new ServletException("Error creating security controller", e);
    }

, , throws Exception. .

+8

ServletException:

try {
    securityController = SecurityControllerFactory.getInstance().create();
} catch (Exception e) {
    throw new ServletException ("Failed to create controller.", e);
}

, , , create.

+3

If you really want to throw them, you can throw an exception at runtime:

try {
   //do stuff
} catch (Exception e) {
   throw new RuntimeException("There was an exception initializing the servlet:  ", e);
}
-1
source

All Articles