Sie sind auf Seite 1von 7

Chapter 8

EXCEPTION-HANDLING
The term exception in Java indicates an exceptional event. It can be defined as an
abnormal event that occurs during program execution and disrupts the normal flow of
instructions. The abnormal event can also be an error in the program.
Errors in a Java program are categorized into two groups:
1. compile-time errors
2. run-time errors
compile-time errors :- Compile-time errors occur when you do not follow the syntax of a
programming language. The compiler detects the syntax error of the program while
compiling the program. For example in Java, you need to terminate every expression
with a semicolon (;). If you do not follow this rule you get a compile time error.

Run-time errors :- Run-time errors occur during the execution of a program. For example,
if the
program runs out of memory, it results in run-time error. if you divide a number by zero
or open a file that does not exist, anexception is raised.
Error handling becomes a necessity when you develop applications that need to take
care of unexpected situations. The unexpected situations that may occur during
program execution are:
􀀃 Running out of memory
􀀃 Resource allocation errors
􀀃 Inability to find files
􀀃 Problems in network connectivity
To handle exceptions, the Java run-time system searches for an exception-handler. In
Java, a catch statement is an exception-handler that is used to handle an exception.
The search for an exception-handler begins with the method in which the exception is
raised. If no appropriate exception-handler is found, the Java run-time system
searches the exception-handler in the next higher method hierarchy. The type of
exception handled by the exception-handler should match the type of exception
thrown. The Java run-time system proceeds with the normal execution of the program
after an exception gets handled. If no appropriate exception-handler is found by the
Java run-time system, the program is terminated.

In Java, the Throwable class is the superclass of all the exception classes. Object
class is the base class of the exception hierarchy. The Exception class and the
Error class are two subclasses of the Throwable class.
The following figure shows the exception hierarchy:
Throwable Class
The Throwable class is a subclass of the Object class. The Throwable class is the
superclass of all the exception objects that are thrown in Java. You can throw only
those exception objects that are derived from the Throwable class. The following
syntax shows how to declare a constructor for the Throwable class:
Throwable()
In the preceding syntax, a new Throwable constructor with no arguments is created.
You can also declare a constructor for the Throwable class with a user-defined
message. The following syntax shows how to declare a constructor of the Throwable
class with a user-defined message:
Throwable(String message)
In the preceding syntax, message represents the specified message included in the
Throwable class.
Exception Class
The Exception class has various subclasses, such as ClassNotFoundException,
IllegalAccessException, and RuntimeException. The ClassNotFoundException
exception is thrown when a class is being referred, but no definition for the class with
the specified name is found. The IllegalAccessException exception is thrown when
a particular method is not found. The RuntimeException exception handles the
exceptions that are raised in the programs during run time.
Error Class
The Error class defines exceptions related to the Java run-time environment. For
example, OutOfMemoryError is an error that occurs when there is insufficient system
memory to execute a program. A program is abruptly aborted when an Error object is
thrown. The Error class consists of two types of constructors, one without any error
message and the other with an error message. The following syntax shows the
constructor of the Error class with no message:
Error()
The following syntax shows the constructor of the Error class having information about
the error:
Error(String message)

The built-in exceptions in Java are categorized on the basis of whether the exception
is handled by the Java compiler or not. Java consists of the following categories of
built-in exceptions:

􀀃Checked Exceptions
􀀃Unchecked Exceptions

Checked Exceptions
Checked exceptions are the objects of the Exception class or any of its subclasses
excluding the Runtime Exception class. Checked exceptions are the invalid conditions
that occur in a Java program due to invalid user input, network connectivity problem,
or database problems. For example, java.io.IOException is a checked exception.
The IOException exception is thrown whenever an input/output operation is
abnormally terminated.
Java uses the try-catch block to handle the checked exceptions. The statements within
a program that throw an exception are placed in the try block. You associate an
exception-handler with the try block by providing one or more catch handlers
immediately after the try block.
Unchecked Exceptions
Unchecked exceptions are the run-time errors that occur because of programming
errors, such as invalid arguments passed to a public method. The Java compiler does
not check the unchecked exceptions during program compilation. For example, if you
divide a number by zero, an unchecked or run-time exception is raised.

When an unexpected error occurs in a method, Java creates an object of the type
Exception. After creating the Exception object, Java sends it to the program by
throwing the exception. The Exception object contains information about the type of
error and the state of the program when the exception occurred. You need to handle
the exception using an exception-handler and process the exception. You can
implement exception-handling in a program by using the following keywords:
􀀃try
􀀃catch
􀀃throw
􀀃throws
􀀃finally

The try block encloses the statements that might raise an exception within it and
defines the scope of the exception handlers associated with it. If an exception is raised
within the try block, the appropriate exception-handler that is associated with the try
block processes the exception.
In Java, the catch block is used as an exception-handler. You enclose the code that
you want to monitor inside a try block to handle a run-time error. A try block must
have at least one catch block that follows it immediately. The catch clause specifies
the exception type that you need to catch. The following code shows an arithmetical
exception with no exception being handled:
class UnhandledException
{
public static void main(String args[])
{
int num1=0, num2=5;
int num3=num2/num1;
System.out.println ("The num3 = " + num3);
}
}
In the preceding code, the default handler of the Java run-time system throws a
raised exception when zero divides a number. It creates an object of the
ArithmeticException exception class.
The output of the preceding code shows that the exception thrown is the object of the
ArithmeticException subclass of the Exception class. The following syntax shows
how to declare the try block:
try
{
// Statements that cause an exception.
}
If an exception is raised within a try block, the appropriate exception-handler that is
associated with the try block handles the exception.
The catch statement takes the object of the Exception class that refers to the
exception caught, as a parameter. When the exception is caught, the statements
within the catch block are executed. The scope of the catch block is restricted to the
statements in the preceding try block only. The following syntax shows how to declare
the try- catch block:
try
{
// Statements that cause an exception.
}
catch(ExceptionName obj)
{
// Error handling code.
}
In the preceding syntax, the catch statement accepts the object of the Exception class
that refers to the exception caught, as a parameter. When the exception is caught, the
statements within the catch block are executed. You can use the following code to try
and catch an arithmetic exception:
class ArithmeticExp
{
public static void main(String args[])
{
int num1=0, num2=5,num3=0;
try
{
num3=num2/num1;
System.out.println("The result=" + num3);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero is performed");
}
}
}
Using Multiple catch Statements
A single try block can have many catch blocks. This is necessary when the try block
has statements that raise different types of exceptions. The following code traps three
types of exceptions:
public class TryCatch
{
public static void main(String args[])
{
int array[] = {0,0};
int num1, num2, result = 0;
num1 = 100;
num2 = 0;
try
{
result = num1/num2;
System.out.println(num1 / array[2]);
//more statements
}
catch(ArithmeticException e)
{
System.out.println("Error... Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error... Out of bounds");
}
catch (Exception e)
{
System.out.println("Some other error");
}
System.out.println("The result is: " + result);
//program proceeds
}
}
In the preceding code, the try block has many statements, each of which can result in
an exception. Three catch blocks follow the try block, and each catch block handles a
different type of exception.

Using the finally Clause


When an exception is raised, the statements in the try block written after the
statement in which the exception occurred are ignored. The finally block is used to
process certain statements, no matter whether an exception is raised or not. The
block of code attached with the finally clause is executed after a try-catch block has
been executed. The following syntax shows how to declare the try-finally block:
try
{
// Block of code
}
finally
{
// Block of code that is always executed irrespective of an
exception being raised or not.
}
If there is a catch block associated with the try block, the finally clause is written after
the catch block. The following syntax shows how to declare the try-catch-finally block:
try
{
// Block of code.
}
catch(execption1 obj1)
{
System.out.println("Exception1 has been raised");
}
catch(exception2 obj2)
{
System.out.println("Exception2 has been raised");
}
finally
{
// Block of code that is always executed irrespective of an
exception being raised or not.
}
The finally block executes whether or not an exception is raised. If an exception is
thrown, the finally block executes even if no catch statement matches the exception.
For example, a file has to be closed irrespective of whether an exception is raised or
not. You can place the code to close the file in both the try and catch blocks.

Das könnte Ihnen auch gefallen