User-defined Exceptions

0
105
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.

Example

// File Name InsufficientFundsException.java
import java.io.*;
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 CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;

private int number;
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance
+= amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
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 BankDemo.java
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println(“Depositing $500…”);
c
.deposit(500.00);
try {
System.out.println(“\nWithdrawing $100…”);
c
.withdraw(100.00);
System.out.println(“\nWithdrawing $600…”);
c
.withdraw(600.00);
}catch(InsufficientFundsException e) {
System.out.println(“Sorry, but you are short $” + e.getAmount());
e
.printStackTrace();
}
}
}

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

BackNext
SHARE
Previous articleReading and writing files