Handling Exceptions Handling Exceptions The parameter must be
Handling Exceptions
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 (Arithmetic. Exception ae) if the exception you expect to occur is a (File. Not. Found. Exception 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. 2
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 Runtime. Exception which can be ignored but you should not ignore them in this course. 3
Exception Handlers • A try statement may have only one catch clause for each specific type of exception. try { number = Integer. parse. Int(str); } catch (Number. Format. Exception nfe) { System. out. println("Bad number format. "); } catch (Number. Format. Exception nfe) // is an ERROR because Number. Format. Exception has already been caught { System. out. println(str + " is not a number. "); } 4
Exception Handlers • The Number. Format. Exception class is derived from the Illegal. Argument. Exception class. – this means that the Illegal. Argument. Exception class is more general than the Number. Format. Exception try { number = Integer. parse. Int(str); } catch (Illegal. Argument. Exception e) { System. out. println("Bad number format. "); } catch (Number. Format. Exception e) // this is an ERROR because the more specific exception follows the more general exception. { System. out. println(str + " is not a number. "); } 5
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: – Bank. Account. java – Negative. Starting. Balance. java – Account. Test. java 7
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. 8
@exception Tag in Documentation Comments • General format @exception Exception. Name Description • Remember: @param @result @author @version/date 9
- Slides: 8