I am very new to exception handling in java, hence this question might seems stupid but please let it be answered. Suppose i have a method A in which some part of code can throw an exception B then what is the difference between catching the exception in the method or writting the method declaration as:-
void A() throws B{
----//----
}
The difference lies in the way you call the method.
If your method signature says
throws Exception, the code that calls your method must deal with theExceptioneither by catching it [via acatchclause] or throw it back [viathrowsclause].If you
catchtheException, you are basically trying to handle theExceptionyourself and the code that calls your method does not have to deal with theException.My advice is as follows:
If you think you can handle and recover from the
Exception, that you shouldcatchand do the needful.If you cannot deal with the
Exceptionproperly that do notcatchit, you must throw it back.NOTE: It is a bad programming style to
catchanExceptionand re-throw it back [although you can do it]. If you wrap theExceptionwith another one, then it is ok. But in this case it must make sense to wrap the Exception with another one.Update: The idea is, no matter what number of layers your application has, somebody has to deal with that
throws Exceptionclause. You cannot just let a StackTrace appear to the user in the middle of his activity with the application. The point to consider is “Can you recover from the error and resume your processing?” If yes, then handle the Exception, else throw it back to the layer that can at least show a meaningful message to the user about what happened.