User defined Exceptions: Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter. While defining a user defined exception, we need to take care of the following aspects:
• The user defined exception class should be a sub class of Exception class (mandatory).
• The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception (Suggested).
throw: ‘throw’ is a keyword used in exception handling mechanism. It is used to raise the errors manually. To throw errors, we need to first create the instances of Exceptions.
· The user defined exceptions must be explicitly thrown using the throw statement whose syntax is
throw ThrowableInstance;
· ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Syntax: The following is the syntax for creating user-defined exception
class exceptionclassname extends Exception
{
exceptionclassname(parameter)
{
//statements
}
public String toString()
{
return String
}
}
Example: For example the below program creates a user defined exception named “InvalidAge” and it is thrown when the value for age is invalid i.e. less than or equal to zero or greater than 100. This exception is caught as we have provided the appropriate catch block.
class InvalidAge extends Exception
{
public String toString()
{
return new String(“The age is not valid”);
}
}
class Test
{
public static void main(String as[])
{
int age = Integer.parseInt(as[0]);
if (age<=0 || age >100)
{
throw new InvalidAge();
System.out.print("Hello”);
}
catch(InvalidAge a)
{
System.out.println("Age not valid”);
}
}
}
The above program produces the following output:
c:/jdk1.5/bin> java Test 120
Age not valid
0 comments:
Post a Comment