Defining own Exceptions

12 November 2007

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

public class InvalidId extends RuntimeException {
 
private String userName;
private int id;
 
public InvalidId()
{}
public InvalidId(int id,String userName, String msg)
{
	super(msg);
	this.userName = userName;
	this.id = 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.

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

Output:

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

del.icio.us:Defining own Exceptions  digg:Defining own Exceptions  spurl:Defining own Exceptions  wists:Defining own Exceptions  simpy:Defining own Exceptions  newsvine:Defining own Exceptions  blinklist:Defining own Exceptions  furl:Defining own Exceptions  reddit:Defining own Exceptions  fark:Defining own Exceptions  blogmarks:Defining own Exceptions  Y!:Defining own Exceptions  smarking:Defining own Exceptions  magnolia:Defining own Exceptions  segnalo:Defining own Exceptions  gifttagging:Defining own Exceptions

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Defining own Exceptions

Leave a Reply