Notes
Slide Show
Outline
1
Chapter 12
  • By
    Tony Gaddis
  • Modified by
  • Elizabeth Adams
2
Chapter Topics
    • Today
    • Exceptions
    • Handling Exceptions
    • Throwing Exceptions
    • Thursday
      • File handling
      • Advanced Topics:
        • Binary Files,
        • Random Access Files, and
        • Object Serialization
3
Exceptions
  • An exception is an object that is generated as the result of an error or an unexpected event.
  • Unhandled exceptions cause programs to bomb.
  • This is not a good thing, particularly if the program is flying a plane or administering radiation, or running a nuclear reactor.
  • Exceptions are runtime NOT compile time errors.
4
Handling Exceptions
  • In Java, exceptions are said to have been “thrown.”  In other languages, they may be “raised.”
  • It is the programmers responsibility to write code that anticipates the occurrence of an exception and keeps the program from crashing.
  • The code that does this is said to “handle” the exception and is called an exception handler.
  • If the programmer doesn’t  write code to “handle the exception”, the  default exception handler does.  It prints an error message and crashes the program which isn’t very satisfactory.


5
Exception Classes
6
Handling Exceptions
  • To handle an exception, you use a try catch block try
    • {
    •   (try block statements...)
    • }
    • catch (ExceptionType ParameterName)
    • {
    •   (catch block statements...)
    • }
  • try block contains code that might cause an exception to occur
  • catch indicates the exception that you expect to catch and how you want to handle it.
7
Catch Blocks
  • A catch clause begins with the key word catch and has a parameter list consisting of the type of the exception  and a variable name.


    • catch (ExceptionType ParameterName)


  • The code between the required curly braces following the catch clause will be executed if the try block throws the referenced exception.
  • The Java Virtual Machine searches for a catch clause that can deal with the exception
8
Handling Exceptions
  • Each exception object has a method named getMessage that can be used to retrieve the default error message for the exception.
  • Example: ExceptionMessage.java is a file in your text on page 728


9
Handling Exceptions
  • The parameter must be of a type that is compatible with the thrown exception’s type
    • this means don’t have a catch (ArithmeticException ae) if the exception you expect to occur is a (FileNotFoundException fnfe) because it won’t catch it.
  • After an exception is handled, the program will leave the catch block and continue execution at the point following it.
10
Polymorphic References To Exceptions
  • When handling exceptions, you can use a polymorphic reference (see page 730) as a parameter in the catch clause but do not do so in this course.
    • This means that although you can catch any exception that is derived from the Exception class  with catch(Exception e) you should not.
  • The exceptions that you must handle are the checked exceptions . They  are derived from the Exception class.
  • There are unchecked exceptions derived from RuntimeException which can be ignored but you should not ignore them in this course.
11
Handling Multiple Exceptions
  • The code in the try block may be capable of throwing more than one type of exception.
  • A separate catch clause needs to be written for each type of exception that could potentially be thrown.
  • The JVM will run the first compatible catch clause it finds.


12
Exception Handlers
  • A try statement may have only one catch clause for each specific type of exception.
    • try
    • {
    •   number = Integer.parseInt(str);
    • }
    • catch (NumberFormatException nfe)
    • {
    •   System.out.println("Bad number format.");
    • }
    • catch (NumberFormatException nfe) // is an ERROR because NumberFormatException has already been caught
    • {
    •   System.out.println(str + " is not a number.");
    • }


13
Exception Handlers
  • The NumberFormatException class is derived from the IllegalArgumentException class.
    • this means that the IllegalArgumentException class is more general than the NumberFormatException
    • try
    • {
    •   number = Integer.parseInt(str);
    • }
    • catch (IllegalArgumentException e)
    • {
    •   System.out.println("Bad number format.");
    • }
    • catch (NumberFormatException e) // this is an ERROR because the more specific exception follows the more general exception.
    • {
    •   System.out.println(str + " is not a number.");
    • }
14
The finally Clause
  • The try statement may have an optional finally clause.
  • If present, the finally clause must appear after all of the catch clauses.
    • try
    • {
    •   (try block statements...)
    • }
    • catch (ExceptionType ParameterName)
    • {
    •   (catch block statements...)
    • }
    • finally
    • {
    •   (finally block statements...)
    • }
15
The finally Clause
  • The finally block is one or more statements,
    • that are always executed after the try block has executed and
    • that are always executed after any catch blocks have executed if an exception was thrown.
  • The statements in the finally block execute whether an exception occurs or not.
16
The Stack Trace
  • The call stack is an internal list of all the methods that are currently executing.
  • A stack trace is a list of all the methods in the call stack.
  • It indicates:
    • the method that was executing when an exception occurred and
    • all of the methods that were called in order to execute that method.

17
Uncaught Exceptions
  • When an exception is thrown, it cannot be ignored.
  • It must be handled by the program, or by the default exception handler.
  • When the code in a method throws an exception:
    • normal execution of that method stops
    • the JVM searches for a compatible exception handler inside the method.
18
Uncaught Exceptions
  • If there is no exception handler inside the method:
    • control of the program is passed to the previous method in the call stack.
    • If that method has no exception handler, then control is passed again, up the call stack, to the previous method.
  • If control reaches the main method:
    • the main method must either handle the exception, or
    • the program is halted and the default exception handler handles the exception.
19
Checked and Unchecked Exceptions
  • There are two categories of exceptions:
    • Unchecked
    •  Checked.
  • Unchecked exceptions  derived from Error, which are thrown when a critical error occurs, should not be handled.
  • Unchecked exceptions derived from RuntimeException should be handled or prevented.
  • Checked exceptions derived from Exception  have to be handled by you.
20
Checked and Unchecked Exceptions
  • If the code in a method can throw a checked exception, the method:
    • must handle the exception, or
    • it must have a throws clause listed in the method header.
  • The throws clause informs the compiler what exceptions can be thrown from a method and avoids a compile time error
21
Throwing Exceptions
  • You can write code that:
    • throws one of the standard Java exceptions, or
    • an instance of a custom exception class that you have designed.
  • The throw statement is used to manually throw an exception.
    • throw new ExceptionType(MessageString);
  • The throw statement causes an exception object to be created and thrown.
22
Throwing Exceptions
  • The MessageString argument contains a custom error message that can be retrieved from the exception object’s getMessage method.
  • If you do not pass a message to the constructor, the exception will have a null message.
    • throw new Exception("Out of fuel");
    • Note: Don’t confuse the throw statement with the throws clause.
  • Text example: DateComponentExceptionDemo.java
23
Creating Exception Classes
  • You can create your own exception classes by deriving them from the Exception class or one of its derived classes.
  • Text example:
    • BankAccount.java
    • NegativeStartingBalance.java
    • AccountTest.java
24
Creating Exception Classes
  • Some examples of exceptions that can affect a bank account:  These should be handled by program not as exceptions.
    • A negative starting balance is passed to the constructor.
    • A negative interest rate is passed to the constructor.
    • A negative number is passed to the deposit method.
    • A negative number is passed to the withdraw method.
    • The amount passed to the withdraw method exceeds the account’s balance.
  • We can create exceptions that represent each of these error conditions but that would be stupid.
25
@exception Tag in Documentation Comments
  • General format
    • @exception ExceptionName Description
  • Remember:
    • @param
    • @result
    • @author