User Defined Exception



Creating Your Own Exceptions

  • User-defined exceptions are created by extending the Exception class.
  • The extended class contains constructors, data members and methods.
  • throw and throws keywords are used while implementing user-defined exceptions.



Defining a Custom Exception Class

Custom exceptions are defined in the exact same way as any other Java class. The only important rule is that an exception must extend the Exception class in the java.lang library. This is done in the same way that any other class extends another.

An example of a user defined exception would be:

class MyException extends Exception
{
}

Points To Remember

  • 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.


// Complete Example Of User-defined-exception

import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount()Your Exception Class { return amount; } } withdraw method is throwing exception 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; } } Below class is handling excepting 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(" Withdrawing $100..."); c.withdraw(100.00); System.out.println(" Withdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } } }

Points To Remember

public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output stream