Exception Handling
Exception Handling
Exception Handling
Exception Handling
By
Ravi Kant Sahu
Asst. Professor
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exception Handling
class Exception
{
public static void main (String arr[])
{
System.out.println(“Enter two numbers”);
Scanner s = new Scanner (System.in);
int x = s.nextInt();
int y = s.nextInt();
int z = x/y;
System.out.println(“result of division is : ” + z); }
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exception Handling
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exception (Class Hierarchy)
• At the root of the class hierarchy, there is a class named
‘Throwable’ which represents the basic features of run-time
errors.
Exception Error
Checked Exception
Unchecked Exception
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Checked Exception
• Checked Exceptions are those, that have to be either caught or
declared to be thrown in the method in which they are raised.
Unchecked Exception
• Unchecked Exceptions are those that are not forced by the
compiler either to be caught or to be thrown.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Commonly used sub-classes of Exception
• ArithmeticException
• ArrayIndexOutOfBoundsException
• NumberFormatException
• NullPointerException
• IOException
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Commonly used sub-classes of Errors
• VirualMachineError
• StackOverFlowError
• NoClassDefFoundError
• NoSuchMethodError
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Uncaught Exceptions
class Exception_Demo
{
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.
• once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• In the previous example, we haven’t supplied any exception handlers
of our own.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Exception Handling
Keywords for Exception Handling
• try
• catch
• throw
• throws
• finally
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
try
• used to execute the statements whose execution may result in
an exception.
try {
Statements whose execution may cause an exception
}
Note: try block is always used either with catch or finally or with
both.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
catch
• catch is used to define a handler.
catch (NumberFormatException n)
{System.out.println("Arguments must be Numeric");}
catch (ArrayIndexOutOfBoundsException a)
{System.out.println("Invalid Number of arguments");}
System.out.println(" remaining program");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Internal working of java try-catch block
Nested Try’s
class NestedTryDemo {
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
}
catch (ArithmeticException e)
{
System.out.println("Div by zero error!");
}
}
catch (ArrayIndexOutOfBoundsException) {
System.out.println("Need 2 parameters!");
}
System.out.println(" remaining program");
}}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Defining Generalized Exception Handler
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Divide{
public static void main(String arr[]){
try {
int a= Integer.parseInt(arr[0]);
int b= Integer.parseInt(arr[1]);
int c = a/b;
System.out.println(“Result is: ”+c);
}
catch (Throwable e)
{
System.out.println(e);
}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling
throw
• used for explicit exception throwing.
throw(Exception obj);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• 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.
• java throw
In this example, we have created the validate keyword
method example
that takes integer value as a parameter. If the age is
less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Case2: You declare the exception
A)In case you declare the exception, if exception does not occur,
the code will be executed fine.
B)In case you declare the exception if exception occures, an
exception will be thrown at runtime because throws does not
handle the exception.
A)Program if exception does not occur
• import java.io.*;
• class M{
• void method()throws IOException{
• System.out.println("device operation performed");
• }
• }
• class Testthrows3{
• public static void main(String args[])throws IOException{//declare exception
• M m=new M();
• m.method();
• System.out.println("normal flow...");
• }
• }
B)Program if exception occurs
• import java.io.*;
• class M{
• void method()throws IOException{
• throw new IOException("device error");
• }
• }
• class Testthrows4{
• public static void main(String args[])throws IOException{//declare exception
• M m=new M();
• m.method();
•
• System.out.println("normal flow...");
• }
• }
• Can we rethrow an exception?
Yes, by throwing same exception in catch block.
• Difference between throw and throws
No. throw throws
• import java.io.*;
• class Parent{
• void msg(){System.out.println("parent");}
• }
•
• class TestExceptionChild extends Parent{
• void msg()throws IOException{
• System.out.println("TestExceptionChild");
• }
• public static void main(String args[]){
• Parent p=new TestExceptionChild();
• p.msg();
• }
• }
2) Rule: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but can declare unchecked exception.
• import java.io.*;
• class Parent{
• void msg(){System.out.println("parent");}
• }
•
• class TestExceptionChild1 extends Parent{
• void msg()throws ArithmeticException{
• System.out.println("child");
• }
• public static void main(String args[]){
• Parent p=new TestExceptionChild1();
• p.msg();
• }
• }
If the superclass method declares an exception
• import java.io.*;
• class Parent{
• void msg()throws ArithmeticException{System.out.println("parent");}
• }
•
• class TestExceptionChild2 extends Parent{
• void msg()throws Exception{System.out.println("child");}
•
• public static void main(String args[]){
• Parent p=new TestExceptionChild2();
• try{
• p.msg();
• }catch(Exception e){}
• }
• }
Example in case subclass overridden method declares same exception
• import java.io.*;
• class Parent{
• void msg()throws Exception{System.out.println("parent");}
• }
•
• class TestExceptionChild3 extends Parent{
• void msg()throws Exception{System.out.println("child");}
•
• public static void main(String args[]){
• Parent p=new TestExceptionChild3();
• try{
• p.msg();
• }catch(Exception e){}
• }
• }
Example in case subclass overridden method declares subclass
exception
• import java.io.*;
• class Parent{
• void msg()throws Exception{System.out.println("parent");}
• }
•
• class TestExceptionChild4 extends Parent{
• void msg()throws ArithmeticException{System.out.println("child");}
•
• public static void main(String args[]){
• Parent p=new TestExceptionChild4();
• try{
• p.msg();
• }catch(Exception e){}
• }
• }
Example in case subclass overridden method declares no exception
• import java.io.*;
• class Parent{
• void msg()throws Exception{System.out.println("parent");}
• }
•
• class TestExceptionChild5 extends Parent{
• void msg(){System.out.println("child");}
•
• public static void main(String args[]){
• Parent p=new TestExceptionChild5();
• try{
• p.msg();
• }catch(Exception e){}
• }
• }
• import java.io.*;
• class Parent{
• void msg()throws Exception{System.out.println("parent");}
• }
Finally
• finally creates a block of code that will be executed after a
try/catch block has completed and before the code following
the try/catch block.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• If a finally block is associated with a try, the finally block will
be executed upon conclusion of the try.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Case1: where exception doesn't occur.
• class TestFinallyBlock{
• public static void main(String args[]){
• try{
• int data=25/5;
• System.out.println(data);
• }
• catch(NullPointerException e){System.out.println(e);}
• finally{System.out.println("finally block is always executed");}
• System.out.println("rest of the code...");
• }
• }
Case2: where exception occurs and not
handled.
• class TestFinallyBlock1{
• public static void main(String args[]){
• try{
• int data=25/0;
• System.out.println(data);
• }
• catch(NullPointerException e){System.out.println(e);}
• finally{System.out.println("finally block is always executed");}
• System.out.println("rest of the code...");
• }
• }
Case3: where exception occurs and handled.
• public class TestFinallyBlock2{
• public static void main(String args[]){
• try{
• int data=25/0;
• System.out.println(data);
• }
• catch(ArithmeticException e){System.out.println(e);}
• finally{System.out.println("finally block is always executed");}
• System.out.println("rest of the code...");
• }
• }
Propagation of Exceptions
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Propagation of Exceptions
class ExceptionPropagation{
public static void main(String [] rk){
ExceptionPropagation ob = new ExceptionPropagation();
ob.third();
System.out.println(“Thank You");
}
} Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Defining Custom Exceptions
• We can create our own Exception sub-classes by inheriting
Exception class.
• The Exception class does not define any methods of its own.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructor for creating Exception
• Exception( )
• Exception(String msg)
• Exception( int t )
• Exception( int I, int j)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Myexception extends Throwable
{
public Myexception(int i)
{
System.out.println("you have entered ." +i +" : It
exceeding the limit");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
public class ExceptionTest {
public void show(int i) throws Myexception {
if(i>100)
throw new Myexception(i);
else
System.out.println(+i+" is less then 100 it is ok");
}
public static void main(String []args){
int i=Integer.parseInt(args[0]);
int j=Integer.parseInt(args[1]);
ExceptionTest t=new ExceptionTest();
try{
t.show(i); t.show(j);
}
catch(Throwable e) {
System.out.println("catched exception is "+e);
}
}
} Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Try with Resource Statement
• JDK 7 introduced a new version of try statement known as
try-with-resources statement.
• This feature add another way to exception handling with
resources management,
• It is also referred to as automatic resource management.
Syntax:
try(resource-specification)
{ //use the resource }
catch(Exception ex) {...}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Try with Resource Statement
• The try statement contains a parenthesis in which one or more
resources is declare.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Checked exception
• are compulsory to handle otherwise compile
time error.
• Two ways to handle: 1. Try catch 2. Using throws
method header
Unchecked Exceptions:
Three ways to handle :1. try catch 2. Using throws
method header 3. JVM will handle automatically
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)