User-defined Exceptions

User-defined Exceptions

Java provides many built-in exception but at many times built-in exceptions are not able to describe a certain situation. In such cases, like the built-in exception, the programmer can also create his own exception which are called user-defined exception.

Before going ahead one must be aware about basics of Exception Handling, which has been explained here.

Now let’s see how we can create User Defined exception-

Steps

1). The user should create an exception class as a subclass to Exception class. Since all exception are subclasses of Exception class, the user should also make his class a subclass to it.

class MyException extends Exception

2). The user can write a default constructor in his own exception class. He can use it, in case he does not want to store any exception details. If user does not want to store any exception details. If the user does not want to create any empty object to his exception class, he can eliminate writing the default constructor.

MyException(){}

3). The user can create a parametrized constructor with a String as a parameter. He can use this to store exception details. He can pull super class (Exception) constructor from this and send the string there.

MyException(String str){
   super(str);  // call Exception class constructor and store str there.
}

4). When the user wants to raise his own exception, he should create an object to his exception class and throw it using throw clause as –

MyException obj = new MyException("Exception details");
throw obj;

Example

package com.c2s.corejava;

public class MyException extends Exception{

	private static final long serialVersionUID = 1L;
	
	private static int account[] = {1000,1001,1002,1003,1004,1005};
	private static String name[] = {"John","Paul","Raj","James","Xavi"};
	private static double balance[] = {1600.00, 1700.00, 1800.00, 1300.00, 1900.00};

	//default constructor
	MyException(){
	}

	//Parameterized constructor
	MyException(String str){
		super(str);
	}

	public static void main(String[] args) {

		try{
			System.out.println("Account No."+"\t"+"Customer"+"\t"+"Balance");
			for(int i=0; i<5; i++ ){
				System.out.println(account[i]+"\t\t"+name[i]+"\t\t"+balance[i]);

				//display user defined exception if balance is less than 1500
				if(balance[i]<1500){
					MyException obj = new MyException("Balance amount is less than 1500 for customer " +name[i]);
					throw obj;
				}

			}
		}catch(MyException me){
			me.printStackTrace();
		}
	}
}

Output

Account No.	Customer	 Balance
1000		John           1600.0
1001		Paul           1700.0
1002		Raj            1800.0
1003        James          1300.0
com.c2s.corejava.MyException: Balance amount is less than 1500 for customer James
	at com.c2s.corejava.MyException.main(MyException.java:29)

 

Stay tuned for more updates !

Leave a Reply

Your email address will not be published. Required fields are marked *