User-defined Exceptions

User-defined exceptions

1User-defined Exceptions

Now you can make your own java exceptions. Keep these points in your mind while writing your own exception classes.
All exceptions should be a child of Throwable
If you wish to write one checked exception which is automatically enforced by the declare or Handle Rule, you required to extend that exception class.
If it’s time to run runtime exception, then you require to extend the RuntimeException Class.

Look below to see how exception is defined below-

We can define our own Exception class as below −

class MyException extends Exception {

You are required to extend that predefined Exception class so to make your own Exception. These are known to be checked exceptions. InsfficientFundsException class is classified as a user-defined exception which extends the Exception class and make it a checked exception. Exception class contains more useful methods and fields.


// File Name
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount = amount;
public double getAmount() {
return amount;

To show sing user-defined exception, the following checking Account contains a withdraw method which throws an InsufficientFundsException.

// File Name
public class CheckingAccount {
private double balance;

private int number;
public CheckingAccount(int number) {
this.number = number;
public void deposit(double amount) {
+= amount;
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
-= amount;
}else {
double needs = amount balance;
throw new InsufficientFundsException(needs);
public double getBalance() {
return balance;
public int getNumber() {
return number;

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

// File Name
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println(“Depositing $500…”);
try {
System.out.println(“\nWithdrawing $100…”);
System.out.println(“\nWithdrawing $600…”);
}catch(InsufficientFundsException e) {
System.out.println(“Sorry, but you are short $” + e.getAmount());

Join all the above mentioned three files and run BankDemo. This will gives the following output:

Previous articleReading and writing files