Exception Handling

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 73

Programming in Java

Exception Handling

By
Ravi Kant Sahu
Asst. Professor

Lovely Professional University, Punjab


Exception
Introduction
• An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's
instructions.

• An exception is an abnormal condition that arises in a code


sequence at run time.

• A Java exception is an object that describes an exceptional (that


is, error) condition that has occurred in a piece of code.

• In other words, “An exception is a run-time error.”

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

• An Exception is a run-time error that can be handled


programmatically in the application and does not result in
abnormal program termination.

• Exception handling is a mechanism that facilitates


programmatic handling of run-time errors.

• In java, each run-time error is represented by an object.

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.

• There are two non-abstract sub-classes of Throwable.


• Exception : can be handled
• Error : can’t be handled

• RuntimeException is the sub-class of Exception.

• Each exception is a run-time error but all run-time errors are


not exceptions.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Throwable

Exception Error

Run-time Exception - VirtualMachine


• IOException - ArithmeticException - NoSuchMethod
• SQLException - ArrayIndexOutOf - StackOverFlow
BoundsException
- NullPointerException

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.

• Unchecked Exceptions either represent common programming


errors or those run-time errors that can’t be handled through
exception handling.

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.

• 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.

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


Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why Exception Handling?
• When the default exception handler is provided by the Java
run-time system , why Exception Handling?

• Exception Handling is needed because:


– it allows to fix the error, customize the message .
– it prevents the program from automatically terminating

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.

• It contains statements that are to be executed when the


exception represented by the catch block is generated.

• If program executes normally, then the statements of catch


block will not executed.

• If no catch block is found in program, exception is caught by


JVM and program is terminated.
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 (ArithmeticException e)
{System.out.println("Second number must be non-zero");}

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

• A generalized exception handler is one that can handle the


exceptions of all types.

• If a class has a generalized as well as specific exception


handler, then the generalized exception handler must be the
last one.

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);

‘throw’ keyword can be used:


• to throw user defined exception
• to customize the message to be displayed by predefined exceptions
• to re-throw a caught exception

• Note: System-generated exceptions are automatically thrown by


the Java run-time system.

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.

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...");
}}
• public class Demo{
• static void validate(int age){
• if(age<18)
• throw new java.io.IOException("not valid");
• else
• System.out.println("welcome to vote");
• }
• public static void main(String args[]){
• validate(13);
• System.out.println("rest of the code...");
• }}
class ThrowDemo
{
static void demo()
{
try {
throw new NullPointerException(“heloooo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demo.");
throw e; // rethrow the exception
}
catch(Exception e)
{
System.out.println("Caught inside demo.");
//in a ladder of catch only one catch can access
}
}
public static void main(String args[])
{
try {
demo();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
}
}
• class ThrowDemo
• {
• static void demo()
• {
• try {
• throw new NullPointerException("heloooo");
• }
• catch(NullPointerException e)
• {
• System.out.println("Caught inside demo.");
• throw e; // rethrow the exception
• }
• catch(Exception e)
• {
• System.out.println("Caught inside demo.");
• //in a ladder of catch only one catch can access
• }
• }
• public static void main(String args[])
• {
• try {
• demo();
• }
• catch(ArithmeticException e)
• {
• System.out.println("Recaught: " + e);
• }
• }
• }
Java Exception propagation

• An exception is first thrown from the top of


the stack and if it is not caught, it drops down
the call stack to the previous method,If not
caught there, the exception again drops down
to the previous method, and so on until they
are caught or until they reach the very bottom
of the call stack.This is called exception
propagation.
• Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).
• class TestExceptionPropagation1{  
•   void m(){  
•     int data=50/0;  
•   }  
•   void n(){  
•     m();  
•   }  
•   void p(){  
•    try{  
•     n();  
•    }catch(Exception e){System.out.println("exception handled");}  
•   }  
•   public static void main(String args[]){  
•    TestExceptionPropagation1 obj=new TestExceptionPropagation1();  
•    obj.p();  
•    System.out.println("normal flow...");  
•   }  
• }  
In this example exception occurs in
m() method where it is not handled,so
it is propagated to previous n()
method where it is not handled, again
it is propagated to p() method where
exception is handled.
Exception can be handled in any
method in call stack either in main()
method,p() method,n() method or m()
method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Program which describes that checked exceptions are not propagated.


• class TestExceptionPropagation2{  
•   void m(){  
•     throw new java.io.IOException("device error");//checked exception  
•   }  
•   void n(){  
•     m();  
•   }  
•   void p(){  
•    try{  
•     n();  
•    }catch(Exception e){System.out.println("exception handeled");}  
•   }  
•   public static void main(String args[]){  
•    TestExceptionPropagation2 obj=new TestExceptionPropagation2();  
•    obj.p();  
•    System.out.println("normal flow");  
•   } }  

• Checked exception must be caught/handled(try catch) or declared(throws)


Java throws keyword
• The Java throws keyword is used to declare an
exception. It gives an information to the programmer
that there may occur an exception so it is better for
the programmer to provide the exception handling
code so that normal flow can be maintained.

Syntax of java throws


return_type method_name() throws exception_class_na
me
{  
//method code  

Keywords for Exception Handling
Throws
• A throws clause lists the types of exceptions that a method might
throw.
type method-name(parameter-list) throws exception-list
{
// body of method
}
• This is necessary for all exceptions, except those of type Error or
Runtime Exception, or any of their subclasses.

• All other exceptions that a method can throw must be declared in


the throws clause. If they are not, a compile-time error will result.
• Throws Keyword is compulsory for checked exceptions
Which exception should be declared
Ans) checked exception only, because:

unchecked Exception: under your control(thro try catch block)


so correct your code.
error: beyond your control e.g. you are unable to do anything if
there occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


• Now Checked Exception can be propagated (forwarded in call
stack).
• It provides information to the caller of the method about the
exception.
• import java.io.IOException;
• public class checked_exeption {
• void m()throws IOException
• {
• throw new IOException("device error");
• }
• void n() throws IOException
• {
• m();

• }
• void p()
• {
• try
• {
• n();
• }
• catch(Exception e)
• {
• System.out.println("exception handled");

• }
• }
• public static void main(String[] args)
• { // TODO Auto-generated method stub
• checked_exeption obj=new checked_exeption();
• obj.p();
• System.out.println("normal flow");
• }}
• import java.io.IOException;
• public class checked_exeption {
• void m()
• {
• try{
• throw new IOException("device error");
• }
• catch(IOException e)
• {
• System.out.println("hello");
• }
• }
• void n()
• {
• m();
• }
• void p()
• {
• n();
• }
• public static void main(String[] args)
• { // TODO Auto-generated method stub
• checked_exeption obj=new checked_exeption();
• obj.p();
• System.out.println("normal flow");
• }
• }
• import java.io.IOException;
• class Testthrows1{
• void m()throws IOException{
• try{
• throw new IOException("device error");//checked exception
• }
• catch(Exception ex) {System.out.println(ex);}
• }
• void n()throws IOException{
• m();
• }
• void p(){
• try{
• n();
• }catch(Exception e){System.out.println("exception handled");}
• }
• public static void main(String args[]){
• Testthrows1 obj=new Testthrows1();
• obj.p();
• System.out.println("normal flow...");
• }
• }
• import java.io.IOException;
• class Testthrows1{
• void m()throws IOException{
• try{
• throw new IOException("device error");//checked exception
• }
• catch(Exception ex) {System.out.println(ex);
• //throw ex}
• }
• void n()throws IOException{
• m();
• }
• void p(){
• try{ // if we will not declare or handle it will give error because If you are calling a method that
declares an exception, you must either caught or declare the exception.
• n();
• }catch(Exception e){System.out.println("exception handled");}
• }
• public static void main(String args[]){
• Testthrows1 obj=new Testthrows1();
• obj.p();
• System.out.println("normal flow...");
• } }
• import java.io.IOException;
• class Testthrows1{
• void m(){
• try{
• throw new IOException("device error");//checked exception
• }
• catch(Exception ex) {System.out.println(ex);}
• }
• void n() {
• m();
• }
• void p(){
• n();
• }
• public static void main(String args[]){
• Testthrows1 obj=new Testthrows1();
• obj.p();
• System.out.println("normal flow...");
• } }
• import java.io.IOException;
• class Testthrows1{
• void m()throws IOException{
• try{
• throw new IOException("device error");//checked exception
• }
• catch(Exception ex) {System.out.println(ex);}
• }
• void n() {
• try{ m();}
• catch(Exception e)
• {System.out.println("Handle the exception..."); }
• }
• void p(){
• n();
• }
• public static void main(String args[]){
• Testthrows1 obj=new Testthrows1();
• obj.p();
• System.out.println("normal flow...");
• } }
• Rule: If you are calling a method that declares an
exception, you must either caught or declare the
exception.

There are two cases:


Case1:You caught the exception i.e. handle the exception using
try/catch.
Case2:You declare the exception i.e. specifying throws with the
method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.

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

1) Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be


propagated using throw only. propagated with throws.

3) Throw is followed by an Throws is followed by class.


instance.
4) Throw is used within the Throws is used with the method
method. signature.
5) You cannot throw multiple You can declare multiple
exceptions. exceptions e.g.
public void method()throws
IOException,SQLException.
ExceptionHandling with MethodOverriding in Java

•There are many rules if we talk about methodoverriding with


exception handling. The Rules are as follows:If the superclass
method does not declare an exception
• If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked
exception but it can declare unchecked exception.
•If the superclass method declares an exception
• If the superclass method declares an exception, subclass
overridden method can declare same, subclass exception or no
exception but cannot declare parent exception.
• If the superclass method does not declare an exception
1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked
exception.

• 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

• 1) Rule: If the superclass method declares an


exception, subclass overridden method can
declare same, subclass exception or no
exception but cannot declare parent
exception.
Example in case subclass overridden method declares parent 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");}
• }

• class TestExceptionChild5 extends Parent{


• void msg() throws IOException {System.out.println("child");}

• public static void main(String args[]){


• Parent p=new TestExceptionChild5();
• try{p.msg();
• }catch(Exception e){}
• }
• }
• Throws Example
import java.io.*;
public class ThrowsDemo
{
public static void main( String args []) throws IOException {
char i;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter character, 'q' to quit");
do{
i = (char) br.read();
System.out.print(i);
}while(i!='q');
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Keywords for Exception Handling

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.

• The finally block will execute whether or not an exception is


thrown.

• If an exception is thrown, the finally block will execute even


if no catch statement matches the exception.

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.

• The finally clause is optional. However, each try statement


requires at least one catch or a finally clause.

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

• If an exception is not caught and handled where it is thrown,


the control is passed to the method that has invoked the
method where the exception was thrown.

• The propagation continues until the exception is caught, or the


control passes to the main method, which terminates the
program and produces an error message.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Propagation of Exceptions
class ExceptionPropagation{    

public void first() {      int data=50/0;     } 


   
public void second(){      first();     } 
   
public void third() {  try{      second();     }
catch(Exception e){ System.out.println(“Done");}    
}    

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.

• It inherits those methods provided by Throwable.

• Thus, all exceptions, including those that we create, have the


methods defined by Throwable available to them.

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)

• A custom exception class is represented by a subclass of


Exception / Throwable.

• It contains the above mentioned constructor to initialize


custom exception object.

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.

• Any object that implements java.lang.AutoCloseable or


java.io.Closeable, can be passed as a parameter to try
statement.
• A resource is an object that is used in program and must be
closed after the program is finished.

• The try-with-resources statement ensures that each resource is


closed at the end of the statement, you do not have to
explicitly close the resources.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
import java.io.*;
class Test {
public static void main(String[] rk) {
try(BufferedReader br=new BufferedReader(
new FileReader("d:\\myfile.txt")))
{ String str;
while((str=br.readLine())!=null) {
System.out.println(str); } }catch(IOException ie)
{ System.out.println("exception"); } } }

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)

You might also like