logo

APSU Notes


Exception Handling

Savitch 9.1-9.3

Topics

9.1 – Basic Exception Handling

Exceptions

  • Programmers often write code assuming that nothing unusual will happen, then add code later for exceptional cases.
  • A exception is an object that signals the occurrence of an unusual event during the execution of a program.
  • Code that generates a exception object throws an exception.
  • Code that detects and deals with an exception handles that exception.
  • A method can throw an exception if there is a special case that some programs treat one way, but others treat another way.

An Exceptional Case

1
2
3
4
5
6
7
8
9
10
11
12
13
Scanner keyboard = new Scanner(System.in);

System.out.println("Enter number of donuts:");
int donutCount = keyboard.nextInt();
System.out.println("Enter number of glasses of milk:");
int milkCount = keyboard.nextInt();

if (milkCount < 1)
  System.out.println("No milk! Go buy some milk"); // can't divide by zero
else {
  System.out.print("You have " + donutCount / (double)milkCount)
  System.out.println(" donuts for each glass of milk. ";
}

An Exceptional Case with Exceptions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Scanner keyboard = new Scanner(System.in);
try {
  System.out.println("Enter number of donuts:");
  int donutCount = keyboard.nextInt();
  System.out.println("Enter number of glasses of milk:");
  int milkCount = keyboard.nextInt();

  if (milkCount < 1)
    throw new Exception("Exception: No milk!");

  System.out.print("You have " + (donutCount / (double)milkCount))
  System.out.println(" donuts for each glass of milk. ";
}
catch(Exception e) {
  System.out.println(e.getMessage());
  System.out.println("Go buy some milk.");
}

Exceptions in Java

  • Java uses a try-throw-catch approach to exceptions.
  • Code that might throw an exception is contained in a try block.
1
try { Code_To_Try }
  • If something unusual happens, an exception object is created and thrown using the throw keyword.
1
throw new Exception(Message);
  • If an exception is thrown in a try block it can be handled by a catch block.
1
catch (Exception e) { Code_To_Handle_Exception }

Exceptions and Control Flow

  • If an exception is thrown in a try block, the rest of the try block is skipped and controls jumps to the corresponding catch block.
  • The exception is assigned to the catch-block parameter, which may be accessed when handling the exception.
1
2
3
4
catch(Exception e) { // e is the catch-block parameter
  System.out.println(e.getMessage());
  System.out.println("Go buy some milk.");
}
  • If no exceptions are thrown in a try block, the catch block is skipped and control jumps to the code immediately after the catch block.

Predefined Exception Classes

  • Many Java classes have methods that may throw predefine exceptions like IOExpectation or ClassNotFoundExpectation.
  • These methods should only be called inside of try block.
  • The corresponding catch block should catch the specific exception.
1
catch (IOException e)
  • To get information about the exception, use the getMessage method to generate a string message.
1
System.out.println(e.getMessage());
  • If the program can not continue after the exception is thrown, the catch block can call System.exit to end the program.

9.2 – Defining Your Own Exception Classes

Defining Your Own Exception Classes

  • A new kind of exception can be defined by creating a new class that derives from the Exception class.
1
2
3
4
5
6
7
8
public class DivideByZeroException extends Exception {
  public DivideByZeroException() {
    super("Divideing by Zero!"); // calls the Exception constructor
  }
  public DivideByZeroException(String message) {
    super(message); // calls the Exception constructor
  }
}
  • The new exception can now be thrown in a program.
1
throw new DivideByZeroException();

The getMessage Method

  • The Exception class defines a getMessage method that returns the string passed to the Exception constructor.
  • The getMessage is inherited by any class that extends Exception, and should not be overridden.
  • To make sure that getMessage works, use super to call the Exception constructor in all derived class constructors.
  • Any new exception class should define both an default constructor, and a one-argument constructor that takes a string message.

9.3 – More About Exception Classes

Declaring Exceptions

  • If a method throws an exception that it does not handle, it must have a throws clause in the header.
1
public void sampleMethod() throws DivideByZeroException
  • Any method that calls sampleMethod must do one of the following:
    • Call it inside of a tryblock with a catch block that handles a DivideByZeroException.
    • Includes a throwscaluse for DivideByZeroException in its own header.
  • A throwscaluse can contain multiple exception types:
1
public int myMethod() throws IOException, DivideByZeroException
  • If a derived class overrides a base-class method that has a throws clause it can not add expectations to throws clause, but it can remove them.

A Method with a throws Clause

1
2
3
4
5
6
7
8
9
10
11
12
13
public void doDivision() throws DivideByZeroException {
  Scanner keyboard = new Scanner(System.in);

  System.out.println("Enter numerator:");
  int numerator = keyboard.nextInt();
  System.out.println("Enter denominator:");
  int denominator = keyboard.nextInt();

  if (denominator == 0)
    throw new DivideByZeroException();
  double quotient = numerator / (double)denominator;
  System.out.println(numerator + "/" + denominator + "=" + quotient);
}

Kinds of Exceptions

  • A checked exception must either be caught in a caught block or declared in a throws clause.
    • Check exceptions indicate serious problem that may require program termination.
    • IOException, ClassNotFoundException,NoSuchMethodExceptionand BadStringOperationException are checked exceptions.
  • A uncheck exception does not need to be caught in a catch block or declared in a throws clause.
    • Unchecked exceptions indicate problems with code that need to be fixed.
    • ArrayIndexOutOfBoundsException, NullPointerException, and ArithmeticException are unchecked exceptions.
    • Unchecked exceptions are derived from the RunTimeException class.

Errors

  • The Exception class derives from the Throwable class.
  • An error in a object of the Errorclass, which is also derives from the Throwable class.
  • Errors do not need to be caught or declared in a throws clause.
  • Most errors indicate a situation that is out of the programmer’s control.
  • An OutOfMemoryError occurs if your program runs out memory.
  • An AssertionError occurs if an assertion check fails.

Multiple Throws and Catches

  • A try block can throw multiple exceptions of possibly different types.
  • Each catch block can catch exceptions of only one type, but multiple catch blocks can follow a try block
1
2
3
4
5
6
7
8
9
10
try {
  // code that may throw a NegativeNumberException
  // code that may throw a DivideByZeroException
}
catch(DivideByZeroException e) {
  // handle DivideByZeroException
}
catch(NegativeNumberException e) {
  // handle NegativeNumberException
}

Tips for Exception Handling

  • Always catch the more specific exception first.
1
2
3
catch(Exception e) { ... } // handles all exceptions
catch(DivideByZeroException e) { ... } // never reached
// the order of the catch clauses should be reversed
  • Bad user input often results in exception being thrown.
  • An exception thrown by a method must be handled the same way regardless of where in the method is was thrown.
  • It is generally good practice to have different methods throw and catch exceptions.
  • It is possible to nest try-catchblocks, but it is usually not necessary and should be avoided.

The finally Block

  • The code in a finally block is always executed whether or not an exception is thrown or caught.
  • A finally block must appear after all catch blocks.
1
2
3
4
5
6
7
8
9
try {
  // code to try executing
}
catch(Exception e) {
  // handle an exception
}
finally {
  // always executed
}

Chapter 9 Summary

  • An exception is an object of a class derived from the class Exception. Descendants of the class Error are not exceptions, but they behave like them.
  • Exception handling allows you to design and code the normal case for your program separately from the code that handles exceptional situations.
  • Java provides predefined exception classes. You can also define your own exception classes.
  • Java has two kinds of exceptions: checked and unchecked (run-time). A method that throws a checked exception must either handle it or declare it in a throws clause within its heading. Checked exceptions must be caught eventually. Otherwise, program execution will terminate. Unchecked, or run-time, exceptions need not be caught or declared in a throws clause and usually are not. Unchecked exceptions belong to classes derived from the class RuntimeException. All other exceptions are checked.
  • Certain Java statements themselves might throw an exception. Methods from class libraries might throw exceptions. You can also explicitly throw an exception in your code by using a throw statement.
  • When a method might throw an exception but not catch it, the exception class usually must be listed in a throws clause for the method.
  • An exception is caught in a catch block.
  • A try block is followed by one or more catch blocks. In this case, always list the catch block for a more specific exception class before the catch block for a more general exception class.
  • Every exception has a getMessage method that can be used to recover a description of the caught exception.
  • Do not overuse exceptions.

Powerpoint

Quiz

Quiz 5, Quiz 7