/*
Write a Java program to implement user defined exception handling
*/
An exception is a run time error. It is an abnormal condition that arises in a code sequence at run time. Error codes are typically used to check errors and handle them manually.
A Java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown from the method that caused the error. This can be caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Working of exception handling
Program statements to be monitored for exceptions are contained within a try block. If an exception occurs within the try block, it is automatically thrown by the Java run-time system or is manually thrown using the keyword throw. Code can be written to catch and handle this exception in some rational manner within the catch block. Any code that absolutely must be executed after a try block completes is put in a finally block. The general form of an exception-handling block is as below:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// …
finally
{
// block of code to be executed after try block ends
}
// ExceptionType is the type of exception that has occurred.
Exception class hierarchy
All exception types are subclasses of the built-in class Throwable. It has two subclasses – Exception and Error. Exception class is used for exceptional conditions that user programs should catch. There are two important subclass of exception – RuntimeException and IOException. Custom exception types can also be created under exception class. Error defines exceptions that are not expected to be caught under normal circumstances by your program.
Using try and catch
Java run-time system provides the default exception handler. It is also useful to manually handle an exception. Doing so provides two benefits:
-
It allows user to manually fix the error.
-
It prevents the program from automatically terminating.
A try and its catch statement form a unit. To guard against and handle a run-time error, simply enclose the code to be monitored inside a try block, followed immediately by a catch clause that specifies the exception type to catch. Example program to illustrate a try block and a catch to process the ArithmeticException generated by the division-by-zero error:
class EH
{
public static void main(String as[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println(“This will not be printed.”);
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println(“Division by zero exception.”);
}
System.out.println(“After catch statement.”);
}
}
// Output:
Division by zero exception.
After catch statement.
The call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. i.e. the catch is not “called,” so execution never “returns” to the try block from a catch.
Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. Example
// Multiple catch statements.
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println(“a = ” + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by 0 error: ” + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error: ” + e);
}
System.out.println(“After try/catch blocks.”);
}
}
Nested try statements
The try statement can be nested inside the block of another try. Example
…
try
{
// code
try
{
// Code
}
catch(Exception e)
{
// Code
}
}
catch(Exception e)
{
// Code
}
…
finally
finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.
-
The finally block will execute whether or not an exception is thrown.
-
If an exception is thrown, the finally block will execute even if no catch statement matches the exception.
-
Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.
This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause. Example
…
try
{
// Code
}
catch (Exception e)
{
// Code
}
finally
{
// Code
}
…
throws
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. This is done by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
User Defined Exceptions:
User Defined Exception are customized exception specifically created by users using their own exception class and ‘throw’ keyword. This can be done by extending the class Exception.
throw keyword
Instead of the exceptions being thrown by the Java run-time system, it is possible for a program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. There are two ways you can obtain a Throwable object:
-
creating one with the new operator.
-
using a parameter in a catch clause