Beginning with java7, to catch multiple exceptions with a single catch, you can use

Beginning with java7, to catch multiple exceptions with a single catch, you can use

In Java, we will use try-catch statement to catch and handle the exceptions. More than one exception type can be generated in try block.

Beginning with Java 7, a new feature called multi-catch has been introduced to allow us to handle multiple exception types with a single catch block.

In this tutorial, we will show you some examples of how we handle multiple exceptions types in Java 6 and Java 7.

What You’ll Need

  • Oracle JDK 1.7 or above

Syntax

This is the syntax of catching multiple exception types in Java 7 or above.

Try {

    // Execute statements that may throw exceptions

} catch (ExceptionType1 | ExceptionType2 | ... VariableName) {

    // Handle exceptions

}

In Java 6 and before, we have to handle multiple exception types with multiple catch block.

NormalCatchExceptionsExample.java

package com.chankok.exception;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class NormalCatchExceptionsExample {

    public static void main(String[] args) {

        try {

            URL url = new URL("http://www.chankok.com/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            System.out.println("Connecting to www.chankok.com");
            System.out.println("Response Code = " + connection.getResponseCode());

            connection.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Java 7 Example

Beginning with Java 7, we can handle multiple exception types with a single catch block. The MalformedURLException and ProtocolException are separated by a pipe character |.

CatchMultipleExceptionsExample.java

package com.chankok.exception;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class CatchMultipleExceptionsExample {

    public static void main(String[] args) {

        try {

            URL url = new URL("http://www.chankok.com/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            System.out.println("Connecting to www.chankok.com");
            System.out.println("Response Code = " + connection.getResponseCode());

            connection.disconnect();

        } catch (MalformedURLException | ProtocolException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Other Resources

  • Oracle – Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
  • Code

In Java, I want to do something like this:

try {
    ...     
} catch (/* code to catch IllegalArgumentException, SecurityException, 
            IllegalAccessException, and NoSuchFieldException at the same time */) {
   someCode();
}

...instead of:

try {
    ...     
} catch (IllegalArgumentException e) {
    someCode();
} catch (SecurityException e) {
    someCode();
} catch (IllegalAccessException e) {
    someCode();
} catch (NoSuchFieldException e) {
    someCode();
}

Is there any way to do this?

asked Aug 16, 2010 at 18:07

This has been possible since Java 7. The syntax for a multi-catch block is:

try { 
  ...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
            NoSuchFieldException e) { 
  someCode();
}

Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.

Also note that you cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is inherited, either directly or indirectly, from ExceptionA. The compiler will complain:

Alternatives in a multi-catch statement cannot be related by subclassing
  Alternative ExceptionB is a subclass of alternative ExceptionA

The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.

M. Justin

11.1k7 gold badges75 silver badges113 bronze badges

answered Aug 16, 2010 at 18:11

OscarRyzOscarRyz

193k110 gold badges379 silver badges564 bronze badges

11

Not exactly before Java 7 but, I would do something like this:

Java 6 and before

try {
  //.....
} catch (Exception exc) {
  if (exc instanceof IllegalArgumentException || exc instanceof SecurityException || 
     exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {

     someCode();

  } else if (exc instanceof RuntimeException) {
     throw (RuntimeException) exc;     

  } else {
    throw new RuntimeException(exc);
  }

}

Java 7

try {
  //.....
} catch ( IllegalArgumentException | SecurityException |
         IllegalAccessException |NoSuchFieldException exc) {
  someCode();
}

answered Aug 28, 2012 at 9:15

user454322user454322

6,9025 gold badges43 silver badges51 bronze badges

9

No, one per customer prior to Java 7.

You can catch a superclass, like java.lang.Exception, as long as you take the same action in all cases.

try {
    // some code
} catch(Exception e) { //All exceptions are caught here as all are inheriting java.lang.Exception
    e.printStackTrace();
}

But that might not be the best practice. You should only catch an exception when you have a strategy for actually handling it - and logging and rethrowing is not "handling it". If you don't have a corrective action, better to add it to the method signature and let it bubble up to someone that can handle the situation.

With JDK 7 and later you can do this:

try {
    ...     
} catch (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) {
    someCode();
}

answered Aug 16, 2010 at 18:09

duffymoduffymo

302k44 gold badges368 silver badges555 bronze badges

9

Within Java 7 you can define multiple catch clauses like:

catch (IllegalArgumentException | SecurityException e)
{
    ...
}

rob

6,0872 gold badges37 silver badges55 bronze badges

answered Aug 16, 2010 at 18:12

Beginning with java7, to catch multiple exceptions with a single catch, you can use

crusamcrusam

6,1105 gold badges40 silver badges67 bronze badges

If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:

try {
   ...
} catch (Exception e) {
   someCode();
}

In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}

The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together. Since Java 7, as per @OscarRyz's answer above:

try { 
  ...
} catch( IOException | SQLException ex ) { 
  ...
}

Beginning with java7, to catch multiple exceptions with a single catch, you can use

answered Aug 16, 2010 at 18:12

Beginning with java7, to catch multiple exceptions with a single catch, you can use

Michael ShopsinMichael Shopsin

1,9652 gold badges25 silver badges41 bronze badges

2

A cleaner (but less verbose, and perhaps not as preferred) alternative to user454322's answer on Java 6 (i.e., Android) would be to catch all Exceptions and re-throw RuntimeExceptions. This wouldn't work if you're planning on catching other types of exceptions further up the stack (unless you also re-throw them), but will effectively catch all checked exceptions.

For instance:

try {
    // CODE THAT THROWS EXCEPTION
} catch (Exception e) {
    if (e instanceof RuntimeException) {
        // this exception was not expected, so re-throw it
        throw e;
    } else {
        // YOUR CODE FOR ALL CHECKED EXCEPTIONS
    } 
}

That being said, for verbosity, it might be best to set a boolean or some other variable and based on that execute some code after the try-catch block.

answered Oct 18, 2013 at 21:04

Oleg VaskevichOleg Vaskevich

12.2k6 gold badges61 silver badges79 bronze badges

1

In pre-7 how about:

  Boolean   caught = true;
  Exception e;
  try {
     ...
     caught = false;
  } catch (TransformerException te) {
     e = te;
  } catch (SocketException se) {
     e = se;
  } catch (IOException ie) {
     e = ie;
  }
  if (caught) {
     someCode(); // You can reference Exception e here.
  }

answered Feb 16, 2015 at 18:08

2

It is very simple:

try { 
  // Your code here.
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
            NoSuchFieldException e) { 
  // Handle exception here.
}

answered Jan 20, 2021 at 12:24

For kotlin, it's not possible for now but they've considered to add it: Source
But for now, just a little trick:

try {
    // code
} catch(ex:Exception) {
    when(ex) {
        is SomeException,
        is AnotherException -> {
            // handle
        }
        else -> throw ex
    }
}

answered Sep 17, 2019 at 19:48

Beginning with java7, to catch multiple exceptions with a single catch, you can use

Dr.jackyDr.jacky

3,2176 gold badges55 silver badges86 bronze badges

Catch the exception that happens to be a parent class in the exception hierarchy. This is of course, bad practice. In your case, the common parent exception happens to be the Exception class, and catching any exception that is an instance of Exception, is indeed bad practice - exceptions like NullPointerException are usually programming errors and should usually be resolved by checking for null values.

answered Aug 16, 2010 at 18:10

Vineet ReynoldsVineet Reynolds

75.1k17 gold badges146 silver badges173 bronze badges

Can we catch multiple exceptions in single catch block?

The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar ( | ). Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final .

Can we use multiple catch when can we use multiple catch?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.

Can we catch multiple exceptions in the catch block C#?

In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.
When catching multiple exceptions that are related to one another through inheritance, you should handle the more specialized exception classes before the more general exception classes. To serialize an object and write it to the file, use this method of the ObjectOutputStream class.