Java Reference
In-Depth Information
User-Defined Exceptions
You can create your own exceptions in Java. In fact, because of the way Java is
designed, you are encouraged to write your own exceptions to represent prob-
lems that can arise in your classes. Keep the following points in mind when
writing your own exception classes:
All exceptions must be a child of Throwable.
■■
If you want to write a checked exception that is automatically enforced
by the Handle or Declare Rule, you need to extend the Exception class.
■■
If you want to write a runtime exception, you need to extend the
RuntimeException class.
■■
You will likely never write a class that directly extends Throwable because
then it will be neither a checked nor a runtime exception. Most user-
defined exception classes are designed to be checked exceptions and
therefore will extend the Exception class. However, if you want to write an
exception that you don't want users to have to handle or declare, make it
a runtime exception by extending the RuntimeException class.
The following InsufficientFundsException class is a user-defined exception
that extends the Exception class, making it a checked exception. An exception
class is like any other class, containing useful fields and methods. In our case,
the name of the exception class pretty much explains it all, but we have added
a field to store the amount of insufficient funds and an accessor method for
viewing this field.
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
Search WWH ::




Custom Search