How to catch more than one exception(multi-catch statement) inside a single catch block (Java JDK 7)

package exceptionhandlingjava7;

import java.sql.SQLException;
 * @author tunatore

public class Main {

public static void main (String args[]){

//instead of coding a try catch block such as the following one

        //try {
        //    …
        //} catch (NullPointerException ex) {}
        //  catch (ArrayIndexOutOfBoundsException ex) { }
        //  catch (SQLException ex) { }
        //  catch (… ex) { }

  // Java JDK 7 users can use multi-catch statement in one line

try {
throw new ArrayIndexOutOfBoundsException();
} catch (NullPointerException | ArrayIndexOutOfBoundsException | SQLException ex) {

Output of the program;

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException
at exceptionhandlingjava7.Main.main(
Java Result: 1
BUILD SUCCESSFUL (total time: 1 seconds)

If you don’t reference JDK 7 API in your project, you will encounter an exception like the following one;
error: multi-catch statement is not supported in -source 1.5

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s