Intro to Exception Handling



Outline

  1. Exception Introduction - reference is Gaddis 12.1
  2. Introduction to PA1.

Exception Handling

Terms

Exception
"An object that is generated as a result of an error or an unexpected event." - Gaddis
Exception handler
"A section of code that gracefully responds to an exception." - Gaddis
Default exception handler
Handles exceptions that have not been handled through application code.  The default exception handler ends the program and prints a "stack trace".
Stack trace
A "report" that may be generated as a result of an exception which shows the list of method calls and lines in a program from which they were called.  The top of the stack is the method and line which threw the exception.
Unchecked exception
An exception that is part of the RuntimeException family.  RuntimeExceptions do not have to be handled in some way by your programs.
Checked exception
All exceptions that are not RuntimeExceptions.  These must be handled or specified in the method header in which they may be thrown.
Handling exceptions
try block
A block of code which may throw an exception.  The try block should be as specific as possible.
catch block
The exception handler.  This block will perform whatever actions are necessary to gracefully handle the exception.
throws clause
A clause added to the method header to specify what exceptions are possible in this method that will not be handled by this method.
Examples of exceptions
    1. ArithmeticException - divide by zero
    2. NoSuchElementException - Scanner
    3. NumberFormatException - Scanner
    4. ArrayIndexOutOfBoundsException - Arrays
    5. NullPointerException - Objects
  1. Up until now
    1. Prevention - check for zero
    2. has methods in Scanner
    3. testing against lengths
  2. Now
    1. Still use prevention if we can.
    2. Exception handling for those exceptions that we anticipate that we may not want to avoid or may not be able to avoid or that are truly exceptional.
  3. Examples
    1. Example1.java
    2. Example2.java
    3. Example3.java