If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

The code looks like:

public void someMethode() throws SomeCheckedException {

    //  code

}

Then later you can deal with the exceptions if you don't wanna deal with them in that method.

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

try {

    // exceptional block of code ...

    // ...

} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.

}

The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

try{    
}catch(MyOwnException me){
}catch(Exception e){
}
Answer from jjnguy on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:
Top answer
1 of 7
133

If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

The code looks like:

public void someMethode() throws SomeCheckedException {

    //  code

}

Then later you can deal with the exceptions if you don't wanna deal with them in that method.

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

try {

    // exceptional block of code ...

    // ...

} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.

}

The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

try{    
}catch(MyOwnException me){
}catch(Exception e){
}
2 of 7
108

While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.

try{
    // IO code
} catch (Exception e){
    if(e instanceof IOException){
        // handle this exception type
    } else if (e instanceof AnotherExceptionType){
        //handle this one
    } else {
        // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
        throw e;
    }
}

However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable

try{
    // IO code
} catch (Throwable t){
    if(t instanceof Exception){
        if(t instanceof IOException){
            // handle this exception type
        } else if (t instanceof AnotherExceptionType){
            //handle this one
        } else {
            // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else if (t instanceof Error){
        if(t instanceof IOError){
            // handle this Error
        } else if (t instanceof AnotherError){
            //handle different Error
        } else {
            // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else {
        // This should never be reached, unless you have subclassed Throwable for your own purposes.
        throw t;
    }
}
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › catch.html
The catch Blocks (The Java™ Tutorials > Essential Java Classes > Exceptions)
The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-try-catch-block
Java Try Catch Block - GeeksforGeeks
June 3, 2025 - The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block. Example: Here, we are going to handle the ArithmeticException using a simple try-catch block.
Top answer
1 of 2
10

It is only good practice to catch a specific exception if it can actually be handled by the catch block.

Very often, programmers assume that the fault can be handled at all, close to the point of occurrence. This is often wrong. To understand why, we need to explore what "handling" means.

Your second snippet:

try {
    // code implementation
} catch (IOException | SQLException | NullPointerException ex ) {
    // handle exception
}

implies that there could be some useful action which could handle the caught exception. But this is often not so. As was noted in the comments, performance is irrelevant if the code gives incorrect results.

About the only thing you can do with a NullPointerException is to log everything salient for debugging and die; any further attempt to continue has a high probability of stomping on the heap and breaking other things down-stream. This exception results from a software defect and cannot be properly handled at all.

I'll assume the code implementation consists of reading a istream. Handling an IOException could be as simple as re-reading the part that threw the exception (if caused by an interrupted system call) but that's the rare case and an over-generalized exception. If the error is FileNotFoundException, you've got an upstream defect which cannot be handled in this context. Who could handle it? The code which created the istream could have handled the exception if there was a reasonable alternative file to open, but the sample snippet should lack the information. If we were trying to open a file with no reasonable alternate, all the opener can do is throw an exception itself.

Why? Because there is a contract between the opening code and its caller that says "you give me a pathname, and I will open it for you and give you an istream". Upon FileNotFoundException, the opening code has failed to fulfill its contract and will induce failures in the caller and other places where the istream is accessed. It is this violation of contract is the strongest case for exceptions.

Let's assume that the FileNotFoundException was thrown in a long running program like an editor. It would be rude for the application to crash just because you typo'ed a filename. In this case, the exception should be allowed to propagate up to the main loop which actually can handle it: namely by informing the user "file not found" thus giving the user an opportunity to try another filename.

When an Exception implies a contract failure that exception must propagate upwards until there is code that can actually rectify the contract failure. If there is no place that failure can be rectified (as in cat not_a_file) the best you can do is print a meaningful error message and (as in cat not_a_file a_file) skip not_a_file.

2 of 2
-5

I would assume that checking for specific exceptions would have an impact in performance (even if it is minimal) because the program would compare the exception triggered with 3 different values, instead jumping straight to the exception clause. This would increase the number of CPU cycles taken, hence reduce performance.

Listing all exceptions does not improve readability or functionality of the code though, so I would suggest you catch all exceptions by default, unless you need to catch an exact type of an exception.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › catch-multiple.html
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
October 20, 2025 - The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:
🌐
BeginnersBook -
beginnersbook.com › home › java › try catch in java – exception handling
Try Catch in Java – Exception handling
May 30, 2024 - Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it can handle all exceptions. This catch block should be placed at the last to avoid such situations.
🌐
Stackify
stackify.com › best-practices-exceptions-java
9 Best Practices to Handle Java Exceptions - Stackify
May 2, 2023 - Always catch the most specific exception class first and add the less specific catch blocks to the end of your list. You can see an example of such a try-catch statement in the following code snippet.
Find elsewhere
🌐
Rollbar
rollbar.com › home › how to catch multiple exceptions in java
3 Ways to Catch Multiple Exceptions in Java (Easy Examples) | Rollbar
August 12, 2024 - Java offers three ways to catch multiple exceptions: using multiple catch blocks for different exception types, the multi-catch feature to handle multiple exceptions in a single block, and a catch-all block for general exception handling.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-catch-multiple-exceptions-rethrow-exception
Java Catch Multiple Exceptions, Rethrow Exception | DigitalOcean
August 3, 2022 - Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev ... While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial. ... Hi Pankaj, Using single catch block how can I differentiate from where my code is getting exception? try{} catch(IOException ie){ ie.printStackTrace();} catch(SQLException se){ se.printStackTrace();} catch(Exception e){ e.printStackTrace();} now it is replaced with catch(IOException| SQLException |Exception e){ e.printStackTrace();} In the above code my doubt is e.printStackTrace() will print which exception class message whether (IOException / SQLException/Exception )?
🌐
GeeksforGeeks
geeksforgeeks.org › java › exceptions-in-java
Java Exception Handling - GeeksforGeeks
Note: When an exception occurs and is not handled, the program terminates abruptly and the code after it, will never execute. In Java, all exceptions and errors are subclasses of the Throwable class.
Published   December 23, 2016
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › basic-try-catch-finally.html
Basic try-catch-finally Exception Handling in Java
If an exception is thrown from ... the call stack to the method that called openFile(). If the calling method has a try-catch block, the exception will be caught there....
🌐
Quora
quora.com › How-can-we-catch-all-exceptions-in-Java-at-once-Is-it-possible-to-do-so
How can we catch all exceptions in Java at once? Is it possible to do so? - Quora
The reason why exception classes exist and you're expected to add even more is that “return -1” and similar constructs don't provide sufficient context and simply printing the stacktrace and shutting down is not acceptable.
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › catching-multiple-exceptions.html
Catching Multiple Exceptions in Java 7
In Java 7 you can catch multiple exceptions using the multi catch syntax: try { // execute code that may throw 1 of the 3 exceptions below.
🌐
CodeGym
codegym.cc › java blog › java exceptions › java try - catch
Java Try - Catch
February 20, 2025 - You can stack multiple catch blocks after a try to handle different types of exceptions. Like, one for `ArithmeticException` (division by zero) and another for `NullPointerException` (oops, forgot to initialize something). It’s like having a plan for every possible hiccup—super efficient and totally doable since Java 7 even lets you catch multiple exceptions in one block with a `|` symbol.
🌐
Dev.java
dev.java › learn › exceptions › catching-handling
Catching and Handling Exceptions - Dev.java
The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception ...
🌐
Rollbar
rollbar.com › home › how to handle exceptions in java
How to Handle Exceptions in Java | Rollbar
September 28, 2022 - In other words, a finally block is executed in all circumstances. For example, if you have an open connection to a database or file, use the finally block to close the connection even if the try block throws a Java exception. try { // block of code that can throw exceptions } catch (ExceptionType1 ex1) { // exception handler for ExceptionType1 // Push the handled error into Rollbar rollbar.error(ex1, "Hello, Rollbar"); } catch (ExceptionType2 ex2) { // Exception handler for ExceptionType2 // Push the handled error into Rollbar rollbar.error(ex2, "Hello, Rollbar"); } finally { // finally block always executes }
🌐
Reddit
reddit.com › r/programmertil › [java] til catch(exception e) doesn't catch all possible errors.
r/ProgrammerTIL on Reddit: [Java] TIL catch(Exception e) doesn't catch all possible errors.
February 14, 2018 -

tldr: Throwable catches errors that Exception misses

So I was trying to write a JavaMail web app and my app was not giving me any outputs. No error or success message on the web page, no errors in Tomcat logs, no email at the recipient address. I added a out.println() statement to the servlet code and manually moved it around the page to see how much of it was working. All my code was wrapped in:

try {} catch (Exception) {}

Realizing that my code was stopping midway through the try block and the catch block wasn't even triggering, I started googling and found this stackoverflow page. Turns out, Exception class is derived from the Throwable class. Changing my catch(Exception e) to catch(Throwable e) and recompiling the project worked. The webpage printed a stacktrace for the error and I was able to resolve it.

🌐
Zero To Mastery
zerotomastery.io › blog › try-catch-java
Beginner's Guide To Try And Catch In Java | Zero To Mastery
Now that division works, Java continues execution and reaches numbers[5], which is out of bounds. This time, it throws an ArrayIndexOutOfBoundsException, which is caught by the second catch block, printing: Invalid array index! That’s exactly why multiple catch blocks exist — so we can handle each potential failure individually rather than dealing with all of them in the same way. So far, we’ve seen how try and catch handle exceptions ...