View RSS Feed

My Java Tips

Defining own Exceptions

Rate this Entry
by , 11-09-2011 at 06:10 PM (537 Views)
Exception is defined as:
"An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions."

This event (exception generation event) can be specific to your requirement as well. Defining own exception makes sense if you want to generate exceptions specific to your logic (business logic). .

Consider following scenario:

You have an environment where student id cannot be 0 or less and cannot be more than 10. If student id is less than or equal to zero, or is greater than 10 - then exception should be raised. For this you have to define your own exception.

If we extend our class from RuntimeException, then we are not supposed to write code under try catch block. Here we will prefer RuntimeException.

We created a class named InvalidId that extends RuntimeException. It is always useful to store the information relevant to the error. So we defined attributes for userName and id. Next we created a constructor that takes 3 input parameters including the message that is to be displayed if exception occurs (msg). Constructor of parent class (RuntimeException) is called with message using super(msg) and this will throw the exception. This has to be the first statement of the constructor.

Java Code:
public class InvalidId extends RuntimeException {

private String userName;
private int id;

public InvalidId()
public InvalidId(int id,String userName, String msg)
	this.userName = userName; = id;
Now we come to the Student class. We have an if condition that will check the id, and if it falls in the non acceptable zone, we will throw the exception.

Java Code:
int id = 0;
String name = "Kamran";

if(id<=0 || id>10)
throw new InvalidId(id,name, "Invalid user id.");
System.out.println("Student data is correct.");

Exception in thread "main" Ex.InvalidId: Invalid user id.
at Ex.Student.main(

Submit "Defining own Exceptions" to Facebook Submit "Defining own Exceptions" to Digg Submit "Defining own Exceptions" to Submit "Defining own Exceptions" to StumbleUpon Submit "Defining own Exceptions" to Google

Tags: None Add / Edit Tags
Java SE