tl;dr Mutlicatch handles things singlehandedly, multiple catch blocks are more flexible and nicer to operations. The two techniques can be combined.

If you have a try statement that can throw many different exception types, you'll want the multiple catch blocks. It's a bit more code but offers far greater flexibility.

For instance, if working with sockets, a SocketException may be caught with nothing more than a reconnect and/or an error message (as something as simple as an inadvertently disconnected cable may cause this)

If a null pointer exception(although it's unchecked) is caught, you're going to want to write to a log and make an emergency landing here, cleaning up what you can, and backtracking quite a bit codewise, possibly.

In addition, this can be subdivided even further, where different types of "common" exceptions may cause different actions to be taken(such as a connection lost vs name not resolved having different implications for the end-user on the first connection attempt) and different "heavy" exceptions being handled in different ways as well.

While you could have one (multiple exception type) catch block, it would either singlehandedly take similar action for all exceptions (presenting a null pointer exception to a user in the same way as a condition based on a cable being unplugged) or require if e instanceof FooException blocks that can decrease readability.

You can also combine the two, multicatching all "common" exceptions into a retry and nice message and all severe exceptions into a forced cleanup and shutdown

You don't want stacktraces for tripped cables, and you don't want to brush off missing objects.

Answer from nanofarad on Stack Overflow
Top answer
1 of 5
10

tl;dr Mutlicatch handles things singlehandedly, multiple catch blocks are more flexible and nicer to operations. The two techniques can be combined.

If you have a try statement that can throw many different exception types, you'll want the multiple catch blocks. It's a bit more code but offers far greater flexibility.

For instance, if working with sockets, a SocketException may be caught with nothing more than a reconnect and/or an error message (as something as simple as an inadvertently disconnected cable may cause this)

If a null pointer exception(although it's unchecked) is caught, you're going to want to write to a log and make an emergency landing here, cleaning up what you can, and backtracking quite a bit codewise, possibly.

In addition, this can be subdivided even further, where different types of "common" exceptions may cause different actions to be taken(such as a connection lost vs name not resolved having different implications for the end-user on the first connection attempt) and different "heavy" exceptions being handled in different ways as well.

While you could have one (multiple exception type) catch block, it would either singlehandedly take similar action for all exceptions (presenting a null pointer exception to a user in the same way as a condition based on a cable being unplugged) or require if e instanceof FooException blocks that can decrease readability.

You can also combine the two, multicatching all "common" exceptions into a retry and nice message and all severe exceptions into a forced cleanup and shutdown

You don't want stacktraces for tripped cables, and you don't want to brush off missing objects.

2 of 5
2

This a choice thing. You want to balance readability, portability, maintainability and also handling different exceptions differently.

So balance the use ... If all your catches use the same block of handling then use the first form, because that's just one code block and you aren't repeating yourself over and over again. The compiler can optimize things out a bit for you.

On the other hand use the second form if you are handling each exception differently.

This is somewhat of a broad question and the answer is dependant on your goals.

🌐
GeeksforGeeks
geeksforgeeks.org › java › multicatch-in-java
Java Multiple Catch Block - GeeksforGeeks
September 22, 2023 - In the following code, we have to handle two different exceptions but take the same action for both. So we needed to have two different catch blocks as of Java 6.0. ... // A Java program to demonstrate that we needed // multiple catch blocks for multiple exceptions // prior to Java 7 import java.util.Scanner; public class Test { public static void main(String args[]) { Scanner scn = new Scanner(System.in); try { int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); } catch (ArithmeticException ex) { System.out.println("Arithmetic " + ex); } catch (NumberFormatException ex) { System.out.println("Number Format Exception " + ex); } } }
Discussions

java - Multiple or Single Try Catch - Stack Overflow
Still, I think your best bet may ... original method - ideally in a single try-catch block. ... It looks very old question. But, my answer would make it relavent because in the recent days Java 7 has added new feature to add multiple exaceptions and the catch block.... More on stackoverflow.com
🌐 stackoverflow.com
Is there such thing as too many try-catch blocks?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
8
29
April 11, 2022
java - Best practice for handling many exceptions - Software Engineering Stack Exchange
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I have Java microservice that exposes multiple APIs. Under each API there are many exceptions could be thrown. The last method that catches them all has big catch block ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
May 29, 2018
Avoiding duplicate code in multi-catch block
If you want the program to exit for any other exception than IOException then have one catch block for IOException and one for just Exception (supertype of all exceptions). Inside the block for IOException you just throw the exception again with the throw keyword. In the other block you exit your application. If you want one catch block for multiple specific exception then you can chain the types in the brackets like this: catch (Exception1 | Exception2 | Exception3 e) Edit: I think I misunderstood what you need after rereading your final paragraph. More on reddit.com
🌐 r/learnjava
2
3
January 24, 2021
🌐
Programiz
programiz.com › java-programming › multiple-exceptions
Java catch Multiple Exceptions
In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe |. ... class Main { public static void main(String[] args) { try { int array[] = new int[10]; ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › technotes › guides › language › catch-multiple.html
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
There are no other preceding catch blocks that can handle it. It is a subtype or supertype of one of the catch clause's exception parameters. The Java SE 7 compiler allows you to specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws.
🌐
W3Schools
w3schools.com › java › java_exceptions_multiple.asp
Java Multiple Exceptions
Since Java 7, you can catch multiple exceptions in one catch block using the | symbol.
🌐
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.
🌐
Tutorialspoint
tutorialspoint.com › java › java_multi_catch_block.htm
Java Multiple Catch Blocks
Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown from a particular code section. A try block can have multiple catch blocks to handle multiple exceptions.
Find elsewhere
🌐
Medium
medium.com › thefreshwrites › catch-multiple-exceptions-in-java-44cc3ea17ad0
Catch Multiple Exceptions In Java | by Mouad Oumous | The Fresh Writes | Medium
February 17, 2024 - Use Multiple Catch Statements in Arguments of A Catch Block: This feature came from Java 7. Here you can handle multiple exceptions under a single catch block (separated by pipe sign) for a corresponding try block.
Top answer
1 of 13
57

I always try to reduce levels of nesting for readability and maintainability. If you have n try/catch blocks, each handling the same type of exception, why not refactor the code that can throw the exception into methods...it would look something like:

try {
    firstBatchOfTricky();
    secondBatchOfTricky();
    ....
    nthBatchOfTricky();
} catch (ItWentBoomException e) {
   // recover from boom
} catch (ItWentBangException e) {
   // recover from bang
}

This is much more readable than having multiple try/catches. Note that your methods should describe what they do in the spirit of self documenting code.

Since you have your own Exception type, you can add the data you need to the exception to do different things in the catch block. When you say 'more specific message', you can just throw the exception with the detailed message; you shouldn't need multiple catch blocks. If you want to do drastically different things based on the state of the exception, just create more exception types and catch blocks but only one try block, as my pseudocode shows...

Finally, if you can't recover from the exception(s), you should not clutter the code with catch blocks. Throw a runtime exception and let it bubble. (Good advice from @tony in the comments)

2 of 13
56

This isn't a performance or personal preferences question: It's a functionality and requirements question.

Suppose I write:

Scenario 1:

try
{
  doThingA();
}
catch (SomeException panic)
{
  System.out.println("doThingA failed");
}
try
{
  doThingB();
}
catch (SomeException panic)
{
  System.out.println("doThingB failed");
}

Scenario 2:

try
{
  doThingA();
  doThingB();
}
catch (SomeException panic)
{
  System.out.println("doThingA or doThingB failed");
}

These two scenarios are not equivalent: They do different things. In Scenario 1, if doThingA throws the exception, doThingB still executes. In Scenario 2, if doThingA throws the exception, doThingB is not executed. So the question is not which gives better performance or which is more readable code, but rather, if doThingA fails, should doThingB still be executed or not?

If what you really want is the second behavior, but you want different messages to tell the user what went wrong, then you should either throw different exceptions, or put the text of the message into the exception, i.e.

void doThingA() throws SomeException
{
  ... whatever code ...
  if (theWorldIsAboutToEnd)
    throw new SomeException("doThingA failed");
}

Then in the catch clause, instead of displaying a constant string, displayt SomeException.toString or SomeException.getMessage.

🌐
Coding Shuttle
codingshuttle.com › java-programming-handbook › multiple-and-nested-try-catch
Multiple and Nested Try-Catch Blocks in Java
April 9, 2025 - Java allows multiple catch blocks to handle different exceptions separately. try { // Risky code } catch (ExceptionType1 e1) { // Handle ExceptionType1 } catch (ExceptionType2 e2) { // Handle ExceptionType2 } catch (Exception e) { // Handle ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-catch-multiple-exceptions-rethrow-exception
Java Catch Multiple Exceptions, Rethrow Exception | DigitalOcean
August 3, 2022 - If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy. Another improvement is done in Compiler analysis ...
🌐
Codefinity
codefinity.com › courses › v2 › 455bd504-41cd-4fd0-98b7-9f3ee575d21a › 7425cfcb-65fa-4ed7-b6b5-510ed254606b › 8e86509c-fb4f-4303-b4d1-1a3b75bd6571
Learn Handling Multiple Exceptions | Exceptions
Java allows us to do that by catching both exception objects in a single catch block. ... 123456789101112131415161718192021222324 package com.example; public class Main { public static void main(String[] args) { try { // Call the method that ...
🌐
Reddit
reddit.com › r/learnjava › is there such thing as too many try-catch blocks?
r/learnjava on Reddit: Is there such thing as too many try-catch blocks?
April 11, 2022 -

I have to make a mini social media app for an assignment, where users can update their status, change their profile picture, change their profile details, or submit a complaint. Any time there's user input like this I have it in a try-catch block since we get deducted major points if our app crashes. Mine doesn't crash when I test it but I'm not sure what kinds of tests our teacher will be putting it through during grading.

Generally speaking are try-catch blocks this the right way to go about this sort of thing? Safeguarding the app from crashing even if the intended functionality doesn't work? Thanks a lot!

Edit: I found all your comments really helpful and will only be implementing try-catch blocks for when a user attempts to upload an image to the app and it's not found. For the string input I'll be validating the input rather than wrapping those methods in try-catch. Really appreciate the help, I learned a lot! Thanks all!

Top answer
1 of 5
25
Yes, it is absolutely such a thing. Generally speaking are try-catch blocks this the right way to go about this sort of thing? Safeguarding the app from crashing even if the intended functionality doesn't work? The question is, do you actually want to safeguard the app from crashing? The thing is, if you try to hide every error then you're making it much more difficult to discover what went wrong. You also leave the user confused about why something isn't working. See it like this: Your app crashing is a symptom of an error. The solution is not to treat the symptom, but the cause - and the cause is the bug or unexpected event that caused the error to begin with. Fix the cause, not the symptom. There are times when you'd want try-catches, like operations where you can't reliably do any checks beforehand. For example, a third-party library is inclined to throw exceptions rather than return results (i.e using exceptions as a secret return). I'm personally much more inclined to let things blow up, but I also go to great lengths making sure that things are well tested so that when they blow up it is due to an actual bug that needs to be dealt with.
2 of 5
7
Generally speaking are try-catch blocks this the right way to go about this sort of thing? Safeguarding the app from crashing even if the intended functionality doesn't work? Terrible practice that will make your app impossible to debug, programs should fail loudly and clearly. It might be closer to the philosophy of bad javascript. Exceptions are to be seen as a different way of passing special information that might need to be handled in another part of the code. For instance let's say you had some code opening a file and returning a handler for it, if exceptions weren't a thing (like in C) you'd be forced to check if the handler was valid: this would turn into a gambled mess of if(handler == null){//} especially if said handler emerges from nested calls as each of them would have to check its validity while exceptions naturally bubble up. In addition to that what if 'null' is already taken as a valid value that the function could return? Do you wrap the return value inside an object that contains information about the success of the operation? What if you want to signal different kinds of exceptions (ex: did the read fail because the file does not exist or because the string in input was null?)?
🌐
Quora
quora.com › Can-we-have-one-try-block-and-multiple-catch-block
Can we have one try block and multiple catch block? - Quora
Answer (1 of 2): Yes, you can have multiple catch blocks with one try but it should be in ascending order i.e. the super class (generic/general) must follow the sub classes i.e. specific exception.
🌐
Coderanch
coderanch.com › t › 399332 › java › multiple-blocks
multiple try blocks (Beginning Java forum at Coderanch)
April 15, 2005 - marc, as always thank you for your reply. Much appreciated! I tried the following code: But I get the following error: C:\java\PoliceDatabase>javac TestApp.java .\VehicleRecord.java:426: 'try' without 'catch' or 'finally' try { ^ 1 error Surely the catch block catches both try blocks?
🌐
Reddit
reddit.com › r/learnjava › avoiding duplicate code in multi-catch block
r/learnjava on Reddit: Avoiding duplicate code in multi-catch block
January 24, 2021 -

I have a try-catch block that handles multiple exception; if an IOException is thrown, the exception will be handled elsewhere in the program and the program will keep running. If any other exceptions are thrown, the program should exit.

So I'd like to to something like this, instead of writing System.exit(1) in every catch block:

void foo() throws IOException {
    try {
        bar(); // Throws IOException as well as Exception 1, 2, 3
    } catch (Exception1 e) {
        logStuff();
    } catch (Exception2 e) {
        logStuff();
    } catch (Exception3 e) {
        logStuff();
    }
    if (Exception 1, 2 or 3 was thrown) {
        System.exit(1);
    }
}

The log messages are specific to each catch block, so I can't group them into one block. So, is there a simple way to avoid multiple System.exit(1)?

🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
The 'try catch' is finished. Try it Yourself » · The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc: