Exception Handling
Exception Handling
Dr Richa
Assistant Professor
Introduction
• Types of Error
• Syntax Error
• Logical Error
• Runtime Error
Introduction
• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
Syntax Error
• The syntax error occurs where some mistakes are done by
programmer, syntactic or grammatical mistakes.
Logical Error
• If a program is not giving as expected results, these kind of error is known
as logical error.
• Example: r=-b/2a; //it will not give any error but it will b=also not give
expected error.
• It should be r=-b/(2*a)
• Another example is
for(i=1;i<Arr.length.i++)
{
System.out.println(A[i]);
}
Runtime Error
• It occurs due to the mishandling of the program, user is not using the
program the way it should be.
• Runtime error occurs at the users end and the cause of error are
• Bad input
• Unavailability of resources.
• In both cases program will crash
• One major problem with runtime error is program will crash
• In case of this situation we need to tell the user that you have done so
and so mistake by using appropriate message.
• Programmer should do the arrangement in the program itself
Exception Handling Construct
Class Test
{
public static void main(String args[])
{
int a,b,c;
a=5;
b=0;
c=a/b;//result is infinity
System.out.println(c);
System.out.println(“End of program”);
}
}
Try catch Syntax
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
//msg to the user if exception occurs
}
Variation of try and catch
• try with multiple catch
• Nested try catch
• Customized message in catch block
Try and catch block
public class Main
public static void main(String[] args)
int a,b,c;
try
{
a=10;
b=0;
c=a/b;
System.out.println("Result "+c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero error ");
}
System.out.println("Bye");
}
}
public class Main
public static void main(String[] args)
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 2 number ");
a=sc.nextInt();
b=sc.nextInt();
try {
c=a/b;
System.out.println("Result "+c);
}
catch(ArithmeticException e) {
System.out.println("Denominator can not be zero ");
}
System.out.println("Bye");
}
}
Nested Catch
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int A[]={30,20,10,40,0};
int c=A[0]/A[1];
System.out.println("Division is"+c);
System.out.println(A[5]);
}
}
Multiple Catch
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int A[]={30,20,10,40,0};
try {
int c=A[0]/A[1];
System.out.println("Division is"+c);
System.out.println(A[5]);
}
catch(ArithmeticException e) {
System.out.println("Denominator should not be 0");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds exception");
}
System.out.println("Bye");
}
}
Various Scenario
• What if two exceptions occurs simultaneously?
• What if the exact exception class is not present in catch argument?
Exception
class
• In java, exceptions are mainly categorized into two types, and they are
as follows.
• Checked Exceptions
• Unchecked Exceptions
• The checked exception is an exception that is checked by the compiler
during the compilation process to confirm whether the exception is
handled by the programmer or not. If it is not handled, the compiler
displays a compilation error using built-in classes.
• The following are a few built-in classes used to handle checked
exceptions in java.
• IOException
• FileNotFoundException
• ClassNotFoundException
• SQLException
• DataAccessException
• InstantiationException
• UnknownHostException
• The unchecked exception is an exception that occurs at the time of
program execution. The unchecked exceptions are not caught by the
compiler at the time of compilation.
• The unchecked exceptions are generally caused due to bugs such as
logic errors, improper use of resources, etc.
• ArithmeticException
• NullPointerException
• NumberFormatException
• ArrayIndexOutOfBoundsException
• StringIndexOutOfBoundsException
Nested try catch block
Try
{
try
{
}
catch(Exception e)
{
}
}
Catch(Exception e)
{
}
Finally Block
• Java finally block is always executed whether an
exception is handled or not.
• If you don't handle the exception, before
terminating the program, JVM executes finally
block (if any).
• When an exception does not occur
• When an exception occur but not handled by the catch block
• When an exception occurs and is handled by the catch block
Example
public class Main
{
public static void main(String[] args)
{
try
{
int a=5,b=0,c;
c=a/b;
}
catch(Exception e)
{
System.out.print("msg: "+e);
}
finally
{
System.out.print("msg from finally: ");
}
}
}
Point to remember
• For each try block there can be only one finally block.
• The finally block will not be executed if the program exits (either
by calling System.exit() or by causing a fatal error that causes
the process to abort).
Nested try Example
Exception Propagation
• If the exception occurs in one method is not handled at suitable point
then it will be transmitted to the calling method as well.
• If calling method has also not handled the exception then it will
further propagate to main as well.
• printStackTrace will help you to track the propagation
public class Main{
public static void m() {
int arr[]={1,2,3};
System.out .println("arr[4]: "+arr[4]);
}
static void n() {
try{
m();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Index over reached");
}
} c
public static void main(String[] args) {
n();
}
}
Throw Exception
• Consider a method where we need to compute the area of rectangle.
• If(length<0 || breadth<0)
throw new Exception(“length and breadth can not be -ve”)
Exception is a built-in class and we are throwing object of exception class with a message.
Since it’s a checked exception so we need to handle it. It will not be handled by compiler.
First of all it should be at the same place where we have thrown and catch at the same
place
The purpose is to throw it to the calling method
If we are not handling in the same line then we declare in the signature that this method
throws exception
Throws
int area( int l, int b) throws Exception
System.out.println("value is "+value);
}
}
•Compile it by: javac AssertionExample.java
•Run it by: java -ea AssertionExample
Stack Unwinding
When an exception is thrown but not caught in a particular scope, the
method-call stack is "unwound," and an attempt is made to catch the
exception in the next outer try block. This process is called stack
unwinding. Unwinding the method-call stack means that the method in
which the exception was not caught terminates, all local variables in
that method go out of scope and control returns to the statement that
originally invoked that method. If a Try block encloses that statement, an
attempt is made to catch the exception. If a try block does not enclose that
statement, stack unwinding occurs again. If no catch block ever catches
this exception and the exception is checked, compiling the program will
result in an error.