Java Exception Handling
Java Exception Handling
Introduction
• Exceptions are events that arise due to the occurrence of
unexpected behavior in certain statements, disrupting the
normal execution of a program.
Exceptions examples,
ArrayIndexOfBoundException
ArithmeticException
FileNotFoundException
IOException
NullPointerException
• Whenever an exception occurs in a method, the runtime environment
identifies the type of exception and throws the object of it.
• If the method does not employ any exception handling mechanism, then the
exception is passed to the caller method.
• If no exception handling mechanism is employed in any call stack methods,
the runtime environment passes the exception object to the default
exception handler.
• The default handler prints the name of the exception followed by stack
trace.
Note: stack trace is record of active stack frames generated by the execution of
a program.
When to use Exception Handling
• Common examples are out-of-range array indices, arithmetic overflow
(i.e., a value outside the representable range of values), division by
zero, invalid method parameters, thread interruption and unsuccessful
memory allocation (due to lack of memory).
Error Exception
AssertionE IoError
rror IndexOutOf NullPointerE ArithmeticExce
BpoundExce xception
ption
ption
StringIndexOutOf ArrayIndexOutOfBoun
BoundEceptioj dException
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception. According to Oracle, there are three types
of exceptions:
– Checked Exception
– Unchecked Exception
– Error
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions.
-ClassNotFoundException -ArrayIndexOutOfBoundException
-NoSuchFileException
-ArithmeticException
-NoSuchMethodException
-FileNotFoundException
-InterruptedException
-IOException -IOException
-IllegalAccessException -NullPointerException
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Stack trace
Java try-catch
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
Java try block must be followed by either catch or finally block.
Java catch block
java catch block is used to handle the Exception.
It must be used after the try block only.
Multiple catch block can be included for single try
try{
//code that may throw exception }
Catch(Exception_class_Nameref) { }
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
class demo {
Public static void main(String args[])
{
Method1( ); }
static void method1()
{
System.out.println(“in method 1, calling method 2”);
Method2();
System.out.println(“returned from method 2”); } In method 1, calling method 2
static void method2() In method 2, calling method 3
{
System.out.println(“in method 2, calling method 3”); In method 3
try { Exception Handled
Method3();} Returned from method 3
Catch(Exception e) Returned from method 2
{
System.out.println(“Exception Handled”); }
System.out.println(“returned from method 3”); }
Static void method3()
{
System.out.println(“in method 3”);
int a=10, b=0;
int c=a/b;
}}
Multiple catch clause
• A single try can have multiple catch clauses, for catching specific
exceptions
• As soon as an exception is thrown, the first appropriate catch clause
is located and the exception is passed to it.
try
{
// Protected code
}
catch(ExceptionType1 e1)
{ // Catch block }
catch(ExceptionType2 e2)
{ // Catch block }
catch(ExceptionType3 e3)
{ // Catch block }
class demo {
Public static void main(String args[])
{ In method 1, calling method 2
Method1( ); } In method 2, calling method 3
static void method1() In method 3
{
System.out.println(“in method 1, calling method 2”); Arithmetic Exception Handled :
Method2(); java.lang.ArithmeicException:/
System.out.println(“returned from method 2”); } by zero
static void method2() Returned from method 3
{ Returned from method 2
System.out.println(“in method 2, calling method 3”);
try {
Method3();}
Catch(ArithmeticException ae) Note:
{ All catch blocks must be ordered
System.out.println(“ Arithmetic Exception Handled”, + ae); } from most specific to most general
Catch(Exception e)
{System.out.println(“Exception Handled”); }
i.e. catch for ArithmeticException
System.out.println(“returned from method 3”); } must come before catch for
Static void method3() Exception .
{
System.out.println(“in method 3”); For example : this order of catch
int a=10, b=0;
int c=a/b;
block will produce an compilation
System.out.println(“method 3 exits”); error
}} catch (exception e){ }
Catch( ArithmeticEception ae)
Java 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.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java throw exception
• Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
Syntax
throw exception;
throw new IOException("sorry device error”);
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Throws keyword
• If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
ie. This clause appears after the method’s parameter list and before the method’s body.
• It contains a comma-separated list of the exceptions that the method will throw if various
problems occur.
Note:
the difference between throws and throw keywords, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.
class demo { When a=4 b=2
Public static void main(String args[]) In method 1, calling method 2
{
Method1( ); }
In method 2, calling method 3
static void method1() In method 3
{ Result =2
System.out.println(“in method 1, calling method 2”); Returned from method 3
Method2(); Returned from method 2
System.out.println(“returned from method 2”); }
static void method2()
{
System.out.println(“in method 2, calling method 3”);
try { When a=4 b=0
Method3(4,0);} In method 1, calling method 2
Catch(Exception e)
{System.out.println(“Exception Handled”, + e); }
In method 2, calling method 3
System.out.println(“returned from method 3”); } In method 3
Static void method3(int a, int b) throws Exception Exception handled:
{ java.lang.ArithmeticException:
System.out.println(“in method 3”); Testing Throw
If(b==0)
throw new ArithmeticException(“testing Throw”);
Returned from method 3
Else Returned from method 2
System.out.println(“Result: ” + a/b);
}}
Finally Block
• The finally block (which consists of the finally keyword, followed
by code enclosed in curly braces), sometimes referred to as the
finally clause, is optional.
• The finally block follows a try block or a catch block. A finally
block of code always executes, irrespective of occurrence of an
Exception.
• Using a finally block allows you to run any cleanup-type statements
that you want to execute, no matter what happens in the protected
code.
A finally block almost always executes, it typically contains resource-release
code. Suppose a resource is allocated in a try block. If no exception occurs, the
catch blocks are skipped and control proceeds to the finally block, which frees
the resource.
Syntax
try
{
// Protected code
}
catch(ExceptionType1 e1)
{ // Catch block }
catch(ExceptionType2 e2)
{ // Catch block }
catch(ExceptionType3 e3)
{ // Catch block }
Finally
{ // The finally block always executes.
}
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
public class ExcepTest
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println("Access element three :" + a[3]); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
Finally
{
a[0] = 6; System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
} Exception Thrown: java.lang.ArrayIndexOutOfBoundException :3
} First Element value: 6
The Finally statement is executed
Note:
• While you declare multiple classes in the try block of try-with-resources statement
these classes are closed in reverse order.
• Except the declaration of resources within the parenthesis everything is the same as
normal try/catch block of a try block.
• The resource declared in try gets instantiated just before the start of the try-block.
• postconditions
-assertions about a program’s state after a method finishes.
• Assertions are boolean expressions that are used to test/validate the code.
• Basically used during testing and development phases
• The first form of the assert statement is
assert expression
which throws an AssertionError if expression is false
The second form is
assert expression1 : expression2;
which evaluates expression1 and throws an AssertionError
with expression2 as the error message if expression1 is false.
Assertion have to be enabled explicitly: they are disabled by
default. We can enable and disable assertions by
-ea enable assertion
-da disable assertion
• Class assertdemo
static void check(int i)
{
assert i>0: “value must be positive”;
System.out.println(“valu fine” +i);
}
Public static void main(String[] args)
{
Check (Integer.parseInt(args[0]));
}
}
• Output\
when i=1
Java –ea AssertDemo 1
Value fine 1
When i=-1
Java –ea AssertDemo -1
Exception in thread “main” java.lang.Assertionerroe:
value must be positive
At AssertDemo.check(AssertDemo.java:4)
At AssertDemo.main(AssertDemo.java:9)
Without Enabling Assertions
Java AssertDemo -1
Value fine 1