If the code in a method can potentially throw a checked exception, then that method must ________.

As mentioned above, if your code might cause a checked exception to be thrown; i.e.,:

  • your code throws a checked exception, or
  • your code ignores a checked exception that might be thrown by a called method
then your method must include a throws clause listing all such exceptions. For example:
    public static void main(String[] args) throws FileNotFoundException, EOFException
    { // an uncaught FileNotFoundException or EOFException may be thrown here }

Only uncaught checked exceptions need to be listed in a method's throws clause. Unchecked exceptions can be caught in a try block, but if not, they need not be listed in the method's throws clause.


TEST YOURSELF #1

Consider the following program (assume that comments are replaced with actual code that works as specified):

    public class TestExceptions {
    
        static void e() {
          // might cause any of the following unchecked exceptions to be thrown:
          // Ex1, Ex2, Ex3, Ex4
        }
        
        static void d() {
          try {
              e();
          } catch (Ex1 ex) {
              System.out.println("d caught Ex1");
          }
        }
        
        static void c() {
          try {
              d();
          } catch (Ex2 ex) {
              System.out.println("c caught Ex2");
              // now cause exception Ex1 to be thrown
          }
        }
        
        static void b() {
          try {
              c();
          } catch (Ex1 ex) {
              System.out.println("b caught Ex1");
          } catch (Ex3 ex) {
              System.out.println("b caught Ex3");
          }
        }
        
        static void a() {
          try {
              b();
          } catch (Ex1 ex) {
              System.out.println("a caught Ex1");
          } catch (Ex4 ex) {
              System.out.println("a caught Ex4");
              // now cause exception Ex1 to be thrown
          }
        }
        
        public static void main(String[] args) {
            a();
        }
    }
    
Assume that this program is run four times. The first time, method e throws exception Ex1, the second time, it throws exception Ex2, etc. For each of the four runs, say what is printed; if an uncaught exception is thrown, say what happens.

solution


How to Define and Throw Exceptions

  • Java exceptions are objects.

  • Define an exception by defining a class, for example:
      public class EmptyStackException extends Exception { }
    There is no need to provide any methods or fields; the class can have an empty body as shown above. Note: New exceptions must be subclasses of Throwable; as discussed above, they are usually subclasses of Exception (so that they are checked).

  • Throw an exception using a throw statement:
      public class Stack {
        ...
        public Object pop() throws EmptyStackException {
          if (empty()) throw new EmptyStackException();
          ...
        }
      }
    Note:
    • Exceptions are objects, so you cannot simply throw "EmptyStackException" -- you must use "new" to create an exception object.
    • Since the pop method might throw the (checked) exception EmptyStackException, that must be included in pop's throws clause.


TEST YOURSELF #2

Question 1: Assume that method f might throw exceptions Ex1, Ex2, or Ex3. Complete method g, outlined below, so that:

  • If the call to f causes Ex1 to be thrown, g will catch that exception and print "Ex1 caught".
  • If the call to f causes Ex2 to be thrown, g will catch that exception, print "Ex2 caught", and then will throw an Ex1 exception.
        static void g() throws ... {
            try {
    	    f();
    	} catch ( ... ) {
                ...
            } ...
        }
    

Question 2: Consider the following method.

    static void f(int k, int[] A, String S) {
        int j = 1 / k;
        int len = A.length + 1;
        char c;
        
        try {
            c = S.charAt(0);
            if (k == 10) j = A[3];
        } catch (ArrayIndexOutOfBoundsException ex) {
            System.out.println("array error");
    	throw new InternalError();
        } catch (ArithmeticException ex) {
            System.out.println("arithmetic error");
        } catch (NullPointerException ex) {
            System.out.println("null ptr");
        } finally {
            System.out.println("in finally clause");
        }
        System.out.println("after try block");
    }
    
Part A.
    Assume that variable X is an array of int that has been initialized to be of length 3. For each of the following calls to method f, say what (if anything) is printed by f, and what, if any, uncaught exceptions are thrown by f.

    A. f(0, X, "hi");
    B. f(10, X, "");
    C. f(10, X, "bye");
    D. f(10, X, null);

Part B.

    Why doesn't f need to have a throws clause that lists the uncaught exceptions that it might throw?

solution


Summary

  • Code that detects errors often does not know how to handle them.
  • Therefore, we need a way to "pass errors up".
  • The best approach is to use exceptions.

  • Java provides both built-in and user-defined exceptions.
  • Exceptions are caught using a try block:
      try {
        // statements (including method calls) that might cause an exception
      } catch ( exception-1 id1 ) {
        // code to handle the first kind of exception
      } catch ( exception-2 id2 ) {
        // code to handle the second kind of exception
      } ...
      } finally {
        // code that will execute whenever this try block does
      }
  • Exceptions are thrown using a throw statement.
  • If an exception is thrown in code that is not inside a try block, or is in a try block with no catch clause for the thrown exception, the exception is "passed up" the call stack.
  • Some exceptions are checked and some are unchecked. If a method might throw one or more checked exceptions, they must be listed in the method's throws clause.
  • Exceptions are objects; they are defined as classes (the class name is the name of the exception) that extend the Exception class.

Solutions to Self-Study Questions

Test Yourself #1

    What is printed for each of the four runs?
    
    	1. d caught Ex1
    	2. c caught Ex2
    	   b caught Ex1
    	3. b caught Ex3
    	4. a caught Ex4
    	   execution stops due to uncaught exception Ex1 thrown in main
    

Test Yourself #2

    Question 1: 
    
               static void g() throws Ex1, Ex3 {
                   try {
                       f();
                   } catch (Ex1 ex1) {
                       System.out.println("Ex1 caught");
                   } catch (Ex2 ex2) {
                       System.out.println("Ex2 caught");
    		   throw new Ex1();
    	       }		
               }
    
    Question 2:
    Part A. 
    
           A. f(0, X, "hi"); 
    		nothing printed
    		throws ArithmeticException
           B. f(10, X, ""); 
    		prints "in finally clause"
    		throws StringIndexOutOfBoundsException
           C. f(10, X, "bye");
    		prints "array error", "in finally clause"
    		throws InternalError
           D. f(10, X, null); 
    		prints "null ptr", "in finally clause", "after try block"
    		
    
    Part B. 
    
    Function f doesn't need to have a throws clause that lists the
    uncaught exceptions that it might throw because only uncaught CHECKED
    exceptions need to be listed in a method's throws clause.  The
    uncaught exceptions that f might throw are all UNCHECKED exceptions.
    

When you write a method that throws a checked exception you must?

If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method.

When an exception is thrown by a method that is executing?

8) When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method.

Which type of statement is used to throw an exception?

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class.

When the code in a try block may throw more than one kind of exception?

When the code in a try block may throw more than one type of exception, you need to write a catch clause for each type of exception that could potentially be thrown. All of the exceptions that you will handle are instances of classes that extend this class.