Learn Java Tutorial for Beginners (Video), Part 36: Multiple Exceptions

In this tutorial we'll take a look at throwing and handling multiple exceptions, plus a look at a popular exam/interview question. Java 7 introduced a new way of handling multiple exceptions; but even if you're still on Java 6, there are things you can do to cut down the amount of work in dealing with those pesky catch clauses.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.



Code for this tutorial:

App.java:

 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;

public class App {

    public static void main(String[] args)  {
        Test test = new Test();
        
        // Multiple catch blocks
        try {
            test.run();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            System.out.println("Couldn't parse command file.");
        }
        
        // Try multi-catch (Java 7+ only)
        try {
            test.run();
        } catch (IOException | ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Using polymorphism to catch the parent of all exceptions
        try {
            test.run();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        
        // Important to catch exceptions in the right order!
        // IOException cannot come first, because it's the parent
        // of FileNotFoundException, so would catch both exceptions
        // in this case.
        try {
            test.input();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    
    }

}

 

Test.java:

 

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;


public class Test {
    public void run() throws IOException, ParseException {
        
        
        //throw new IOException();
        
        throw new ParseException("Error in command list.", 2);
        
        
    }
    
    public void input() throws IOException, FileNotFoundException {
        
    }
}