Try with Resource Statement

Try with Resource Statement

java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.

Try with Resource Statement

JDK 7 introduces a new version of try statement known as a try-with-resources statement. This feature adds another way to exception handling with resources management, it is also referred to as automatic resource management.
Try with Resource Statement

Syntax
try(resource-specification)
{
//use the resource
}catch()
{...}
This try statement contains a parenthesis in which one or more resources is declared. Any object that implements orjava.lang.AutoCloseablejava.io.Closeable, can be passed as a parameter to try statement. A resource is an object that is used in a 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.

Example without using try with Resource Statement

import java.io.*;
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));   
while((str=br.readLine())!=null)
 {
System.out.println(str);
 }      
br.close(); //closing BufferedReader stream
}catch(IOException ie)
{  System.out.println("exception");  }
 }
}

Example using try with Resource Statement

import java.io.*;
class Test
{
public static void main(String[] args)
{
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");  }
}
}
NOTE: In the above example, we do not need to explicitly call a methodclose() to close the BufferedReader stream.

throw Keyword

throw keyword is used to throw an exception explicitly. The only object of the Throwable class or its subclasses can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching the type of exception.
throw Keyword in java

Syntax :
throw ThrowableInstance

Creating Instance of Throwable class

There are two possible ways to get an instance of class Throwable,
  1. Using a parameter in the catch block.
  2. Creating an instance with a new operator.
    new NullPointerException("test");
    
    This constructs an instance of NullPointerException with name test.

Example demonstrating throw Keyword

class Test
{
 static void avg() 
 {
  try
  {
   throw new ArithmeticException("demo");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Exception caught");
  } 
 }

 public static void main(String args[])
 {
  avg(); 
 }
}
In the above example, the avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement.

throws Keyword

Any method capable of causing exceptions must list all the exceptions possible during its execution so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword.
Syntax :
type method_name(parameter_list) throws exception_list
{
 //definition of method
}

NOTE: It is necessary for all exceptions, except the exceptions of type Error and RuntimeException, or any of their subclass.

Example demonstrating throws Keyword

class Test
{
 static void check() throws ArithmeticException
 {
  System.out.println("Inside check function");
  throw new ArithmeticException("demo");
 }

 public static void main(String args[])
 {
  try
  {
   check();
  }
  catch(ArithmeticException e)
  {
   System.out.println("caught" + e);
  }
 }
}

finally clause

A final keyword is used to create a block of code that follows a try block. A finally block of code always executes whether or not an exception has occurred. Using a final block, lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A final block appears at the end of a catch block.
finally clause


















Example demonstrating finally Clause

Class ExceptionTest
{
 public static void main(String[] args)
 {
  int a[]= new int[2];
  System.out.println("out of try");
  try 
  {
   System.out.println("Access invalid element"+ a[3]);
   /* the above statement will throw ArrayIndexOutOfBoundException */
  }
  finally 
  {
   System.out.println("finally is always executed.");
  }
 }
}
Output :
Out of try
finally is always executed. 
Exception in thread main java. Lang. exception array Index out of bound exception.  
You can see in above example even if an exception is thrown by the program, which is not handled by the catch block, still finally block will get executed.




























































Comments