Java User-Defined Exception


In Java, you can create your own exception which is called user-defined exception (or) custom exception.

 

While writing your own exception classes you should remember the following points.

 

  • All exceptions should be a child of Throwable.
  • When you're going to write a checked exception, then you need to extend the Exception class.
  • When you're going to write a runtime exception, then you need to extend the RuntimeException class.

Syntax:

 class MyException extends Exception {
}

Example

File Name: InsufficientStocksException.java

import java.io.*;
// User-defined exception
public class InsufficientStocksException extends Exception {
   private double amount;
   public InsufficientStocksException(double amount) {
      this.amount = amount;
   }
   public double getAmount() {
      return amount;
   }
}  

File Name: CheckingStock.java

 import java.io.*;

public class CheckingStock {
   private double balance;
   public void StockIn(double amount) {
      balance += amount;
   }
   public void StockOut(double amount) throws InsufficientStocksException {
      if(amount <= balance) {
         balance -= amount;
      }else {
         double needs = amount - balance;
         throw new InsufficientStocksException(needs);
      }
   }
}

File Name: Retailshop.java

 public class Retailshop {
   public static void main(String [] args) {
      CheckingStock cs = new CheckingStock();
      System.out.println("Stock available is 100");
      cs.StockIn(100);
      try {
         System.out.println("\n Stock Out is 200");
         cs.StockOut(200);
      } catch (InsufficientStocksException e) {
         System.out.println("Sorry, there is Insufficient Stocks is" + e.getAmount());
         e.printStackTrace();
      }
   }
}

Output

Stock available is 100
Stock Out is 200
Sorry, there is Insufficient Stocks is 100
InsufficientStocksException
         at CheckingStock.StockOut(CheckingStock.java:8)
         at Retailshop.main(Retailshop.java:10) 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.