If I put a try/catch in a throws function, in case of an exception which one runs?

  1. Does it do whatever in catch clause, throws an exception or both?

  2. Adding some more details, what if the exception in the inner scope is inherited form the other or vice versa?

  3. What does this function when post doesn't include a parameter?

Example :

 public void doPost(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException{
        int number;
    try {
            number = Integer.parseInt(getParameter(req,"number"));
        } catch (Exception e) {
    number = 5;
        }
    }

where getParameter is a function in my BaseServlet class which extends HttpServlet:

protected String getParameter(HttpServletRequest req, String parameter)
    throws ServletException {
    String value = req.getParameter(parameter);
    if (isEmptyOrNull(value)) 
        throw new ServletException("Parameter " + parameter + " not found");

    return value.trim();
}
有帮助吗?

解决方案

If you choose to both handle the exception (using try/catch) and duck the exception(using throws clause), compiler chooses to handle the exception. In your case, it will catch the exception and assign 5 to number.

And a Suggestion:

its a bad practice to handle all exceptions inside a single catch block, i.e.,

catch(Exception e)

always catch most Specific exceptions.

其他提示

The catch clause will handle any Exception thrown in the body of the try block, effectively rendering the throws declaration pointless.

In other words, if the call to getParameter throws a ServletException, number will be set to 5 and no exception will be thrown beyond the body of that try-catch statement.

It does exactly what's written there:

  1. getParameter() will throw ServletException

  2. This exception will escape from getParameter()

  3. Inside try/catch in doPost() it will be caught

  4. catch block will handle it by calling number = 5.

You are chatching all Exceptions,
so if everything ok. number gets the value from parseInt().

If that will throw any Exception (usually NumberFormatException, or your ServeletException) then you
reach the Exception causem and get

the value 5

Your try-catch block will always run, unless a Throwable is provoked by your try block.

getParameter() will throw ServletException. The catch clause in post(..) will handle any Exception thrown in the body of the try block

It will execute the line:

number = 5;

but i don't see what you do with number...

I will also sugest that you refactor it to:

catch (ServletException e) {
    number = 5;
} 

Only catch the exception that you are expecting...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top