Exceptions
Discuss PA4 Design
Review
All exceptions inherit from
Throwable
Errors and Exception are direct descendents
RuntimeException is unchecked. All others are checked
try / catch blocks allow you to handle an exception that arises during program execution
a throws clause can tell the user of the method that we are not handling an exception
Only exceptions named in the catch block are handled. All others will pass to the JVM default exception handler
But, we know from polymorphism that a more general catch will catch all of its own and its children.
But we can use the more specific catch to differentially handle different situations that arise.
New - Creating an exception
Create an exception the same way that you do any other class, except
You need to extend Exception or one of its children
Only do so if you have something that a standard exception cannot handle.
Use the constructor to pass a more detailed message to the parent exception.
New - Throwing an exception
You can throw an exception as a result of a problem in a method
The throw operator takes an exception object as its operand
The throw operation aborts execution of the current method and sends the exception message to the calling method
It is up to the calling method to handle or rethrow the exception
Examples
AccountTest.java
,
BankAccount.java
,
NegativeStartingBalance.java
SalesReport.java
,
SalesData.txt
SalesReport2.java
StackTrace.java
Practice
worksheet.doc
Department of Computer Science
Nancy Harris Home Page
Current Classes Link