Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Aug 10, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Catching Exceptions

Do you have to individually catch each exception that a method may throw? Or can you just have one generalized catch? For example, can I do this?:
    method1 //which throws exception1
    method2 //which throws exception2
catch(Exception e){

No, you do not have to catch each individual exception and you may have a generalized catch statement such as the one you present. However, this is not a good habit to get into. Sometimes, when you're quickly prototyping an application, you may do this in order to more quickly get to the point at which you start testing your code. In general it is a bad idea because you will not know what exception has occurred and you will therefore not be able to properly handle the exception.

One case where it is justified is where you've properly handled all checked exceptions, but in order to keep your program from crashing, you wrap the code in a thread with a try/catch to catch all RuntimeExceptions. You should only do this when you can gurantee robust recovery. Do not take this to mean that you have to cach every SocketException, ConnectException, EOFException, etc. It is perfectly acceptable to just catch an IOException if every SocketException, ConnectException, EOFException, etc. will be handled in exactly the same way.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date