Learn Java Tutorial for Beginners (Video), Part 35: Throwing Exceptions

In this tutorial we'll take a look at how to throw your own exceptions in Java. Throwing an exception is a useful thing to do when your method encounters an unexpected error; the exception will immediately return from your method, enabling you to handle the problem further up the call stack.

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:

 
public class App {

    public static void main(String[] args) {
        
        Test test = new Test();
        
        try {
            test.run();
        } catch (ServerException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        
    }

}

 

ServerException.java:

 
public class ServerException extends Exception {

    public ServerException(String message) {
        super(message);
    }

}
 

Test.java:

 
import java.io.IOException;


public class Test {

    public void run() throws ServerException {
        
        // Some kind of return value from some complex process!
        // 0 = success
        // anything else = error code
        int code = 1;
        
        if(code != 0) {
            // Something's wrong!
            //throw new IOException("Could not connect to server.");
            throw new ServerException("Could not connect to server.");
        }
        
        System.out.println("Running successfully.");
    }
}