EXCEPTION HANDLING
Definition:
An Exception is an event that occurs during program
execution which disrupts the normal flow of a
program. It is an object which is thrown at runtime.
Occurrence of any kind of exception in java
applications may result in an abrupt termination of
the JVM or simply the JVM crashes.
DIFFERENCE BETWEEN EXCEPTION AND ERROR:
[Link]. Exception Error
1. Exceptions can be recovered Errors cannot be recovered
2. Exceptions are of type Errors are of type [Link]
[Link]
Exceptions can be classified into two types: There is no such classification for errors. Errors are
3. a) Checked Exceptions always unchecked.
b) Unchecked Exceptions
In case of Checked Exceptions, compiler will have In case of Errors, compiler won’t have knowledge of
knowledge of checked exceptions and force to keep try… errors. Because they happen at run time.
catch block. Unchecked Exceptions are not
4.
known to compiler
because they occur at run time.
Exceptions are mainly caused by the application itself. Errors are mostly caused by the
5. environment in which application is running.
Examples: Examples: [Link],
Checked Exceptions: SQLException, IOException [Link]
Unchecked Exceptions:
6.
ArrayIndexOutOfBoundsException,
NullPointerException
Advantage of using Exceptions:
Maintains the normal flow of execution
of the application.
Exceptions separate error handling
code from regular code.
Benefit: Cleaner algorithms, less clutter
Meaningful Error reporting.
Exceptions standardize error handling.
KEY WORDS
Multiple catch blocks
Multiple catch is used to handle many different kind of exceptions
that may be generated while running the program. i.e more than
one catch clause in a single try block can be used.
Rules:
At a time only one Exception can occur and at a time only one
catch block is executed.
All catch blocks must be ordered from most specific to most
general i.e. catch for ArithmeticException must come before catch
for Exception.
public class MultipleCatchBlock2 { public static void main(String[] args) {
try
{
int a[]= {1,5,10,15,16};
[Link]("a[1] = "+a[1]);
[Link]("a[2]/a[3] = "+a[2]/a[3]);
[Link]("a[5] = "+a[5]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
a[1] = 5
a[2]/a[3] = 0
ArrayIndexOutOfBounds Exception occurs rest of the code
Nested Try Block
Definition: try block within a try block is known as nested try block.
Why use nested try block?
Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such
cases, exception handlers have to be nested.
If an inner try statement does not have a matching catch statement
for a particular exception, the control is transferred to the next try
statement’s catch handlers that for a matching catch statement.
If none of the catch statement match, then the Java run-time system
will handle the exception.
THROWING AND CATCHING EXCEPTIONS
Before catching an exception, it is must to throw
an exception first. This means that there should be
a code somewhere in the program that could catch
exception thrown in the try block.
An exception can be thrown explicitly
[Link] the throw statement
[Link] the throws statement
1: Using the throw statement
A program can explicitly throw an exception using the throw statement
besides the implicit exception thrown.
We can throw either checked, uncheked exceptions or custom(user
defined) exceptions
When throw statement is called:
1)It causes the termination of the normal flow of control of the program code
and stops the execution of the subsequent statements.
2)It transfers the control to the nearest catch block handling the type of
exception object thrown
3)If no such catch block exists, then the program terminates.
The general format of the throw statement is as follows:
throw <exception reference>;
1)public class ThrowDemo
2){
3)static void validate(int age)
4){
5)if(age<18)
6)throw new ArithmeticException("not valid");
7)else
8)[Link]("welcome to vote");
9)}
10)public static void main(String args[])
11){
12)validate(13);
13)[Link]("rest of the code...");
14)}
}
OUTPUT
Exception in thread "main" [Link]: not valid at
[Link]([Link])
at [Link]([Link])
Using throws keyword:
The throws statement is used by a method to specify the
types of exceptions the method throws.
If a method is capable of raising an exception that it does
not handle, the method must specify that the exception
have to be handled by the calling method.
This is done using the throws clause. The throws clause
lists the types of exceptions that a method might throw.
Syntax:
Return-type method_name(arg_list) throws exception_list
{
// method body
}
Example:
[Link] [Link];
[Link] class ThrowsDemo
3.{
[Link] void divide(int num, int din) throws ArithmeticException
5.{
[Link] result=num/din;
[Link]("Result : "+result);
8.}
[Link] static void main(String args[])
10.{
[Link] n,d;
[Link] in=new Scanner([Link]);
[Link]("Enter the Numerator : ");
14.n=[Link]();
[Link]("Enter the Denominator : ");
16.d=[Link]();
[Link]
18.{
[Link](n,d);
20.}
[Link](Exception e)
22.{
[Link](" Can't Handle : divide by zero ERROR");
24.}
[Link](" ** Continue with rest of the code ** ");
26.}
27.}
Output:
Enter the Numerator : 4
Enter the Denominator :
0
Can't Handle : divide by zero ERROR
** Continue with rest of the code **
Enter the Numerator :
6
Enter the Denominator :
2
Result : 3
** Continue with rest of the code **
Built-in Exceptions
Checked Exceptions:
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler.
Checked Exceptions forces programmers to deal with the exception that may be thrown.
The compiler ensures whether the programmer handles the exception using try.. catch () block or
not. The programmer should have to handle the exception; otherwise, compilation will fail and error
will be thrown.
Example:
[Link]
[Link]
[Link],
[Link].
[Link]
[Link]
[Link]
Unchecked Exceptions(RunTimeException):
The unchecked exceptions are just opposite to the checked
exceptions.
Unchecked exceptions are not checked at compile-time rather
they are checked at runtime.
The compiler doesn’t force the programmers to either catch the
exception or declare it in a throws clause.
In fact, the programmers may not even know that the exception
could be thrown.
Example:
[Link]
[Link]
NullPointerException
class Main {
public static void main(String args[]) { int x =
0;
int y = 10; int z = y/x;
}
}
Output:
Exception in thread "main"
[Link]: / by zero at
[Link]([Link])
USER-DEFINED EXCEPTIONS (CUSTOM EXCEPTIONS)
Exception types created by the user to describe the exceptions related to their
applications are known as User-defined Exceptions or Custom Exceptions.
To create User-defined Exceptions:
[Link] a self-describing *Exception class name.
[Link] if the exception should be checked or unchecked.
Checked : extends Exception
Unchecked: extends RuntimeException
[Link] constructor(s) that call into super class constructor(s), taking message
that can be displayed when the exception is raised.
[Link] the code that might generate the defined exception inside the try-catch
block.
[Link] the exception of user-defined type is generated, handle it using throw
clause as follows:
throw ExceptionClassObject;
public class EvenNoException extends Exception else
{ {
EvenNoException(String str) EvenNoException exp=new
EvenNoException(arr[i]+" is not an Even
{
Number");
super(str); // used to refer the superclass throw exp;
constructor }
} }
catch(EvenNoException exp)
public static void main(String[] args) {
{ [Link]("Exception thrown is
"+exp);
int arr[]={2,3,4,5};
}
int rem; } // for loop
int i; } // main()
for(i=0;i<[Link];i++) } // class
{
rem=arr[i]%2; Output:
try
2 is an Even Number
{ Exception thrown is EvenNoException: 3
if(rem==0) is not an Even Number 4 is an Even
{ Number
[Link](arr[i]+" is an Even Number"); Exception thrown is EvenNoException: 5
} is not an Even Number