Exception
Exception
An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a run-time error.
A Java exception is an object that describes an exceptional (that is, error) condition
that has occurred in a piece of code. When an exceptional condition arises, an object
representing that exception is created and thrown in the method that caused the error.
Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code. Exceptions thrown by Java relate to fundamental errors
that violate the rules of the Java language or the constraints of the Java execution
environment. Manually generated exceptions are typically used to report some
error condition to the caller of a method.
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable
is at the top of the exception class hierarchy. Immediately below Throwable are two
subclasses that partition exceptions into two distinct branches. One branch is headed
by Exception. This class is used for exceptional conditions that user programs should
catch. This is also the class that you will subclass to create your own custom exception
types. There is an important subclass of Exception, called RuntimeException.
The other branch is topped by Error, which defines exceptions that are not expected
to be caught under normal circumstances by your program. Exceptions of type are stem errors
Stack overflow is an example of such an error.
Java exception handling is managed via five keywords:
try, catch, throw, throws and finally.
Program statements that you want to monitor for exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown. Your code can catch this exception
(using catch) and handle it in some rational manner. System-generated exceptions are
automatically thrown by the Java run-time system. To manually throw an exception, use the
keyword throw. Any exception that is thrown out of a method must be specified as such by a
throws clause. Any code that absolutely must be executed before a method returns is put in a
finally block.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
Uncaught Exceptions
class Exc0 {
public static void main(String args[])
{ int d = 0;
int a = 42 / d;
}}
When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception. This causes the execution of to stop, because
once an exception has been thrown, it must be caught by an exception handler and dealt with
immediately.
Any exception that is not caught by your program will ultimately be processed by the default
handler. The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, andterminates the program.
Notice that 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.
Put differently, catch is not “called,” so execution never “returns” to the try block from
a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch
statement has executed, program control continues with the next line in the program
following the entire try/catch mechanism.
A try and its catch statement form a unit. The scope of the catch clause is restricted
to those statements specified by the immediately preceding try statement. A catch
statement cannot catch an exception thrown by another try . The statements that are protected
by try must be surrounded by curly braces.
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, you can 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.
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: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}}
This program will cause a division-by-zero exception if it is started with no command-
line parameters, since a will equal zero. It will survive the division if you provide a
command-line argument, setting a to something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the
program attempts to assign a value to c[42].
Nested try Statements
The try statement can be nested. That is, a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception is
pushed on the stack. If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try statement’s catch handlers
are inspected for a match. This continues until one of the catch statements succeeds, or
until all of the nested try statements are exhausted. If no catch statement matches, then
the Java run-time system will handle the exception. Here is an example that uses
nested try statements:
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
As you can see, this program nests one try block within another. The program
works as follows. When you execute the program with no command-line arguments, a
divide-by-zero exception is generated by the outer try block. Execution of the program
by one command-line argument generates a divide-by-zero exception from within the
nested try block. Since the inner block does not catch this exception, it is passed on
to the outer try block, where it is handled. If you execute the program with two
command-line arguments, an array boundary exception is generated from within
the inner try block. Here are sample runs that illustrate each case:
throw
The Java ‘throw’ keyword is used to throw an exception explicitly.
So far, you have only been catching exceptions that are thrown by the Java run-time
system. However, it is possible for your program to throw an exception explicitly,
using the throw statement. This is used for program debugging.We can throw an object of any
predefined Exception class or user defined Exception class.
A user can create an exception object manually by extending the topmost exception class
‘Exception’ as follows
class TestUserException
{
public static void main(String args[])
{
MyException me=new MyException(“From Me”)
try{ throw me;
}
}catch(MyException e){
System.out.println(e);
} }
}
throws
Java’s Built-in Exceptions
Inside the standard package java.lang, Java defines several exception classes.
Exception classes are devided into 2 types.
1. Unchecked Exceptions.
The compiler does not check to see if a method handles or throws these
exceptions.
Examples are
ArithmeticException - Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException- Array index is out-of-bounds.
ArrayStoreException - Assignment to an array element of an incompatible type.
IllegalArgumentException -Illegal argument used to invoke a method.
NullPointerException - Invalid use of a null reference.
NumberFormatException - Invalid conversion of a string to a numeric format.
SecurityException - Attempt to violate security.
StringIndexOutOfBounds - Attempt to index outside the bounds of a string.
Checked Exceptions
The compiler will check to see if a method handles or throws these exceptions.
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.You do this by including a throws clause in the method’s
declaration. A throws clause lists the types of checked exceptions that a method
might throw.
M m=new M();
try{ m.method();
Java finally block is a block that is used to execute important code such as
closing network connection, database etc.
class TestFinallyBlock
{
public static void main(String args[])
{
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{System.out.println(e);
}
throw new ArithmeticException();
finally
{
System.out.println("rest of the code...");
System.out.println("finally block is always executed");
}
}
}