Although Java’s built-in exceptions handle most common errors, but sometimes you would probably want to create your own exception types to handle situations specific to your applications. For this just define a subclass of Exception which is, of course, a subclass of Throwable . Your subclasses don’t need to actually implement anything—it is their existence in the type system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. But inherit those methods provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined by Throwable available to them. You may also wish to override one or more of these methods in exception classes that you create.
Methods Defined by Throwable
getStackTrace () Provides programmatic access to the stack trace information printed by printStackTrace() . | |
void | |
void | printStackTrace (PrintStream s) Prints this throwable and its backtrace to the specified print stream. |
void | printStackTrace (PrintWriter s) Prints this throwable and its backtrace to the specified print writer. |
void | setStackTrace (StackTraceElement[] stackTrace) Sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace() and related methods. |
Example
// Demonstrate user defined exception
class MyException extends Exception
{
private int x;
MyException(int a)
{
x=a;
}
public String toString()
{
return("MyException [ " + x + "]");
}
}
class ExceptionDemo1
{
static void compute(int a) throws MyException
{
System.out.println(" called compute : "+a);
if(a>10)
throw new MyException(a);
System.out.println("Exit");
}
public static void main(String args[])
{
try
{
compute(11);
}
catch(MyException e)
{
System.out.println("Error : "+e);
}
}
}
Posted by: Ruchita Pandya
well said about user defined exception..java training in chennai
ReplyDeleteThanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.
Delete