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 myself, the throws
should be used when the caller has broken their end of the contract (passed object) and the try-catch
should be used when an exception takes place during an operation that is being carried out inside the method. Is this correct? If so, what should be done on the callers side?
P.S: Searched through Google and SO but would like a clear answer on this one.
Q #1) When to use throws throw VS try-catch in Java? Answer: The “throws” keyword is used to declare the exception with the method signature. The throw keyword is used to explicitly throw the exception. The try-catch block is used to handle the exceptions thrown by others.
4. throws: The throws keyword is used for exception handling without try & catch block.
Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.
Throw, and Try...Catch... The try statement defines a code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.
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).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With