Printable Version Printable Version

Custom Exception in Java

May 26th, 2009 | By admin | Category: Java

When a program violates the constraints of Java programing language , Java virtual machine(JVM) throws an error signal to the program. These signals are known as Exception in Java programing language. Excpetions are of two types. Checked (Compile-time) exception and un-checked(run-time) exception. JVM has a collection of exceptions that will be thrown at compile time with the exception message and the print stack trace. A developer can create their own exception which is closely related to the application he or she is developing.
To create a custom exception , the custom exception class has to extend java.lang.Exception class.

public class MyException extends Exception{
// Your code goes here.
}

Lets take an example of an application which transfers the money from one account to another.The application enforces two constraints while the transfer take place.
constraints 1 : The amount of money to be transferred should be greater than 100 rs. (INR) per transaction.
constraints 2 : The amount of money to be transferred should be lesser than 25,000 rs (INR) per transaction.
Lets create a MoneyTransferException class which extends java.lang.Exception class

Listing 1 : MoneyTransferException.java

package com.etechguide.java.exception;
public class MoneyTransferException extends Exception {
private static final long serialVersionUID = 1L;
public MoneyTransferException() {
// Constructor without a message
super();
}
public MoneyTransferException(String transferMsg){
// Constructor with a message
super(transferMsg);
}
}

Now we need two different kind of exceptions that can be thrown when,
1. Transfer amount reached below 100 rs. (MinMoneyTransferException)
2. Transfer amount reached above 25,000 rs. (MaxMoneyTransferException)
Lets create both the classes which extends MoneyTransferException created in Listing 1.

Listing 2 : MinMoneyTransferException.java

package com.etechguide.java.exception;
public class MinMoneyTransferException extends MoneyTransferException {
private static final long serialVersionUID = 1L;
public MinMoneyTransferException() {
super();
System.out.println("Minimum limit has been reached");
}
public MinMoneyTransferException(String minTransferMsg){
super(minTransferMsg);
}
}

Listing 3 : MaxMoneyTransferException.java

package com.etechguide.java.exception;
public class MaxMoneyTransferException extends MoneyTransferException {
private static final long serialVersionUID = 1L;
public MaxMoneyTransferException() {
super();
System.out.println("Max limit has been reached..");
}
public MaxMoneyTransferException(String maxTransferMsg){
super(maxTransferMsg);
}
}

Now we will use these two exceptions in our program to validate that no transaction should take place if it violates the above constraints.

Listing 4 : MoneyTransferTest.java


package com.etechguide.java.exception;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MoneyTransferTest {

/**
* A method which transfer money
* @param amount - to be transferred
* @throws MinMoneyTransferException - If amount is less than 100
* @throws MaxMoneyTransferException - If amount is greater than 25000
*/
private void transferMoney(long amount) throws
MinMoneyTransferException, MaxMoneyTransferException{

// Transfer should occur is the amount to be transferred
// is within the range of 100 and 25000.

if(amount >= 100 && amount <= 25000){
System.out.println("Transfer amount is correct");
System.out.println("System is ready for transfer");
}
// Amount is less than 100. Lets throw an exception
//, i.e , MinMoneyTransferException
if(amount <100){
throw new MinMoneyTransferException
("The amount "+amount+" rs. is too less to transfer.Minimum limit is 100 rs.");
}

// Amount is greater than 25000.
// Lets throw an exception , i.e , MaxMoneyTransferException

if(amount > 25000){
throw new MaxMoneyTransferException
("The amount "+amount+" rs. is more than 25,000 rs.Maximum limit is 25,000 rs.");
}
System.out.println("Money has been transferred successfully");
}

// Main method

public static void main(String[] args) {
MoneyTransferTest moneyTransferTest = new MoneyTransferTest();
// prompt the user to enter the Transfer amount
System.out.print("Enter the transfer amount: ");
// open up standard input
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
String amount = null;
// read the amount from the command-line
try {
amount = br.readLine();
Long amountL = new Long(amount);
moneyTransferTest.transferMoney(amountL.longValue());
} catch (MinMoneyTransferException e) {
System.out.println(e.getMessage());
} catch (MaxMoneyTransferException e) {
System.out.println(e.getMessage());
} catch (IOException ioe) {
System.out.println("IO error trying to read the amount!");
System.exit(1);
}
}

}

Lets run the program MoneyTransferTest.java in Listing 4 for three different amount of transfer,
80 rs , 23434 rs and 34564 rs.
Output (for 80 rs):
Enter the transfer amount: 80
The amount 80 rs. is too less to transfer.Minimum limit is 100 rs.
Output (for 23434 rs):
Enter the transfer amount: 23434
Transfer amount is correct
System is ready for transfer
Money has been transferred successfully
Output (for 34564 rs):
Enter the transfer amount: 34564
The amount 34564 rs. is more than 25,000 rs.Maximum limit is 25,000 rs.

  • Share/Save/Bookmark
Tags: ,

5 comments
Leave a comment »

  1. Hi, gr8 post thanks for posting. Information is useful!

  2. Thanks Kelly.
    - admin
    Please do share your valuable learnings.Lets make this blog more useful.
    http://etechguide.in

  3. Hello! Thanks for the post. It is really amazing! I will definitely share it with my friends.

  4. Hi, Just one question. In the above example of ‘MinMoneyTransferException.java’, in the constructor method with ‘String maxTransferMsg’ as argument, what difference does it make if instead of calling the superclass method ’super(..)’, we rather ‘throw’ the superclass exception? Like

    public class MaxMoneyTransferException extends MoneyTransferException {
    private static final long serialVersionUID = 1L;
    public MaxMoneyTransferException() {
    super();
    System.out.println(”Max limit has been reached..”);
    }
    public MaxMoneyTransferException(String maxTransferMsg){
    throw MoneyTransferException(maxTransferMsg); // here you throw the exception
    }
    }

    Also, another Qn ( this might look silly!!)
    Can a method in an Exception class throw to itself?
    If ‘no’, is it because it might lead to an infinite loop?

  5. Hello Kedar,
    You can always throw an exception from the constructor instead of the super(). Difference would be in case of making object of the MaxMoneyTransferException class. If you are throwing the MoneyTransferException from the constructor of MaxMoneyTransfer , you have to catch it or re-throw it while creating the object(using the exception in reality) of MaxMoneyTransfer. Have a look at the Listing – 4 , line number 36 . You need to have a try catch there and re throw the Money Transfer exception. Another issue could be while extending the MaxMoneyTransferException.

    For you second question , you would get a Runtime exception. It is like , throwing the exception – catching it – throwing it back again. An this would go on till stack overflow happen.

    Hope the answers are clear to you.

    Thanks ,
    -Tapas

Leave Comment