Intro to Exception Handling
Outline
- Exception Introduction -
reference is Gaddis 12.1
- 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
- ArithmeticException
-
divide by zero
- NoSuchElementException
-
Scanner
- NumberFormatException
-
Scanner
- ArrayIndexOutOfBoundsException
- Arrays
- NullPointerException
- Objects
- Up until now
- Prevention - check for zero
- has
methods in Scanner
- testing against lengths
- Now
- Still use prevention if we
can.
- 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.
- Examples
- Example1.java
- Example2.java
- Example3.java