08-1
1
CSC 143 Java
More on Exceptions
2
Review
- Can throw exceptions to indicate unusual or erroneous
conditions
- Create an object to hold data about the kind of exception
- Can be an instance of any subclass of Throwable
- Throw it
- Can catch exceptions of desired kinds
- Exceptions help to separate the error-handling code from the
regular code
3
Generic Exceptions
- So far, only throw exceptions of standard exception classes
[such as??]
private void updateBalance( double amount) { if (this.balance + amount < 0) { throw new IllegalArgumentException("insufficient funds"); } else { this.balance = this.balance + amount; } }
- To catch this error, must catch all
IllegalArgumentExceptions... any drawbacks???
4
Custom Exceptions
- A better way would be to create a special kind of exception,
just for the error condition that's being reported
private void updateBalance( double amount) { if (this.balance + amount < 0) { throw new InsufficientFundsException( ); } else { this.balance = this.balance + amount; } }
- Think of two reasons why that's good...