Listing 7: Illustrates use of exceptions in Java

import java.util.*;

class MyError extends Exception {}

public class Deep3 {
    static long seed;

    static void f() throws MyError {
        System.out.println("doing f...");
        g();
    }

    static void g() throws MyError {
        System.out.println("doing g...");
        h();
    }

    static void h() throws MyError {
        Random r = new Random(seed);
        if (r.nextInt(2) != 0)
            throw new MyError();
        System.out.println("doing h...");
    }

    public static void main(String[] args) {
        seed = Long.parseLong(args[0]);
        try {
            f();
        }
        catch (MyError x) {
            System.out.println("MyError occurred");
        }
        System.out.println("back in main");
    }
}

/* Output of "java Deep3 1":
doing f...
doing g...
MyError occurred
back in main
*/