Chapter 16 - Exceptions
Exception Handling
- An object that defines an unusual or erroneous situation
- Attempting to divide by zero
- Array index out of bounds
- File not found
- I/O operation that could not be completed correctly
- Follow a null reference
- Violate a security measure
When an exception occurs a program can:
- Not handle the excpetion
- Handle the exception where it occurs
- Handle the exception at another point in the program
-
Uncaught Exceptions
- Program ends and produces a message that exception occurred
try-catch
-
The programmer can provide code that will be executed when an exception occurs.
-
The exception must be caught
- a try-catch stataement is used to:
try - a block of code that should be "attempted"
catch - a block of code that is executed if the attempt fails
- See Program 16-1 from author's slides
Exception Propagation
- If exception not caught and handled where it occurs, then
propogated to calling
method
keep propogating to caller until caught
- Three methods - level1 calls level2, level2 calls level3
- exception in level3
- caught in level1
- Exception Class can be created
- A programmer can define an exception to handle errors seemlessly
Examples