Exceptions: Multi-catch Tutorial

There will often be occasions where you may need to catch more than one exception. You can have multiple catch statements with each one specifying a single exception class and then a code block for handling the exception. This could lead to a lot of redundant code. With a multi-catch statement you can catch multiple exceptions in the same statement.
A multi-catch statement looks like this:
catch ( NullPointerException | IndexOutOfBoundsException | InvalidArgumentException e) { ... }

Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>md MultiCatch
C:\Java>cd MultiCatch
C:\Java\MultiCatch>Notepad MultiCatch.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.

import java.io.*;
class MultiCatch {
static String fileName;
    public static void main(String args[]) {
        fileName = "c:\\Java\\Hello.txt";
        try {
            File f = new File(fileName); // throws NullPointerException
            f.createNewFile(); // throws IOException or SecurityException
            System.out.println("Created file c:\\Java\\Hello.txt");
        } catch ( NullPointerException | IOException | SecurityException e ) {
            System.out.println("Unable to create Hello.txt ... " + e);

Now switch back to the command prompt (CMD) and type in javac MultiCatch.java and press Enter.
Now type in java MultiCatch and press Enter.

C:\Java\MultiCatch>javac MultiCatch.java
C:\Java\MultiCatch>java MultiCatch
Created file c:\Java\Hello.txt

Final thoughts

Multi-catch can save a lot of duplicated code.