What is the general rule of thumb when deciding whether to add a throws
clause to a method or using a try-catch
?
From what I\'ve read mysel
If you use a try catch, when the exception occurs, the remaining codes would be still executed.
If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.
try-catch pair is used when you want to provide customise behaviour, in case if exception occurs.....in other words...you have a solution of your problem (exception occurrence) as per your programme requirements.....
But throws is used when you don't have any specific solution regarding the exception occurrence case...you just don't want to get abnormal termination of your programme....
Hope it is correct :-)
In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions
can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException
in this case.
And it should catch an exception from a called method it if:
DAO
uses Hibernate
for persisting my entities, so I catch all HibernateExceptions
locally and convert them into my own exception types).