Defining an Exception

Defining an Exception


Posted in : Core Java Posted on : October 9, 2010 at 6:53 PM Comments : [ 0 ]

This section describes about the Defining Exceptions in java.

Defining an Exception

Although , most of exceptions are handled by Java's built-in exceptions, You can also create your own exception types to handle situations specifications specific to your applications.

This can be implemented as follows :

Define a subclass of Exception (which is, of course, a subclass of Throwable). The Exception class does not defined any methods of its own. It does , of course , inherit those methods provided by Throwable. Thus , all exceptions, including those that you create  have the methods defined by Throwable available to them.

Example :

The following example declares a new subclass of Exception and then uses that subclass to signal an error condition in a method. It override the "toString()" method , allowing the description of the exception to be displayed using println().


class MyException extends Exception {
	private int detail;

	MyException(int a) {
		detail = a;
	}

	public String toString() {
		return "MyException[" + detail + "}";

	}
}

class ExceptionDemo {
	static void compute(int a) throws MyException {
		System.out.println("Called computer(" + a + "]");
		if (a > 10)
			throw new MyException(a);
		System.out.println("Normal exit");
	}

	public static void main(String args[]) {
		try {
			compute(1);
			compute(20);

		} catch (MyException e) {
			System.out.println("Caught " + e);
		}
	}
}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac ExceptionDemo .java

C:\Program Files\Java\jdk1.6.0_18\bin>java ExceptionDemo
Called computer(1)
Normal exit
Called computer(20)
Caught MyException[20]

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics