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) {
ex.printStackTrace();
}
}
}

Output of the program;

run:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException
at exceptionhandlingjava7.Main.main(Main.java:25)
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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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