0% found this document useful (0 votes)
48 views

Exception Handling Fundamentals

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Exception Handling Fundamentals

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Exception Handling Fundamentals

Exception is an object that describes an exceptional conditions that has occurred in a piece of
code.
An exceptional conditions arises, an object representing that exception is created and thrown in
the method that caused the error.
Method may choose the handle the exception itself or pass it.
At some point the exception is caught and processed.
Exception 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.
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 after a try block completes 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
}
// ...
finally {
// block of code to be executed after try block ends
}

Here, ExceptionType is the type of exception that has occurred.

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. Exceptions of this type are automatically defined for
the programs that you write and include things such as division by zero and invalid array
indexing.

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 Error are used by the
Java run-time system to indicate errors having to do with the run-time environment, itself. Stack
overflow is an example of such an error. This chapter will not be dealing with exceptions of
type Error, because these are typically created in response to catastrophic failures that cannot
usually be handled by your program.

Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is useful to see what happens
when you don’t handle them. This small program includes an expression that intentionally causes
a divide-by-zero error:
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 Exc0 to stop,
because once an exception has been thrown, it must be caught by an exception handler and dealt
with immediately. In this example, we haven’t supplied any exception handlers of our own, so
the exception is caught by the default handler provided by the Java run-time system. 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, and terminates the program.
Here is the exception generated when this example is executed:

java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)

Notice how the class name, Exc0; the method name, main; the filename, Exc0.java; and the line
number, 4, are all included in the simple stack trace. Also, notice that the type of exception
thrown is a subclass of Exception called ArithmeticException, which more specifically
describes what type of error happened. As discussed later in this chapter, Java supplies several
built-in exception types that match the various sorts of run-time errors that can be generated.
ry and catch both are Java keywords and used for exception handling. The try block is used to
enclose the suspected code. Suspected code is a code that may raise an exception during
program execution.
For example, if a code raise arithmetic exception due to divide by zero then we can wrap that
code into the try block.

try{
int a = 10;
int b = 0
int c = a/b; // exception
}
The catch block also known as handler is used to handle the exception. It handles the
exception thrown by the code enclosed into the try block. Try block must provide a catch handler
or a finally block. We will discuss about finally block in our next tutorials.
The catch block must be used after the try block only. We can also use multiple catch block with
a single try block.

try{
int a = 10;
int b = 0
int c = a/b; // exception
}catch(ArithmeticException e){
System.out.println(e);
}

class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a = 0;
b = 10;
c = b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Multiple catch blocks
A try block can be followed by multiple catch blocks. It means we can have any number of catch
blocks after a single try block. If an exception occurs in the guarded code(try block) the
exception is passed to the first catch block in the list. If the exception type matches with the first
catch block it gets caught, if not the exception is passed down to the next catch block. This
continue until the exception is caught or falls through all catches.
Multiple Catch Block Syntax

try
{
// suspected code
}
catch(Exception1 e)
{
// handler code
}
catch(Exception2 e)
{
// handler code
}

The multiple catch blocks are useful when we are not sure about the type of exception during
program execution.

class Demo{
public static void main(String[] args) {
try
{
Integer in = new Integer("abc");
in.intValue();

}
catch (ArithmeticException e)
{
System.out.println("Arithmetic " + e);
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception " + e);
}
}
}

You might also like