If I put a try/catch in a throws function, in case of an exception which one runs?
-
Does it do whatever in catch clause, throws an exception or both?
-
Adding some more details, what if the exception in the inner scope
is inherited form the other or vice versa? -
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
5tonumber.And a Suggestion:
its a bad practice to handle all exceptions inside a single catch block, i.e.,
always catch most Specific exceptions.