Exception Handling (Java version specific)
Try with Resource Statement
JDK 7 introduces try-with-resources statement.
This feature adds another way to exception handling with resources management. It is also
referred to as automatic resource management. The try-with-resources statement makes sure that every opened resource is closed at the end of the statement. So a try-with-resources statement is nothing but a try statement that declares one or more resources. A resource is said to be any object that implements java.lang.
AutoCloseable interface
Generally finally block is used to close all the resources (viz., file, database connection etc)
1)reduced number of lines.
2)Code looks very neat.
3)Finally block is not required if its sole purpose is just to close the resources.
4)Automatic resource management.
try(resource-specification(may more than one resource))
{
//use the resource
}catch()
{...}
public class TryWtResources{
public static void main(String[] args) {
try(BufferedReader br = new BufferedReader(new FileReader("C://test.txt")))
{
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
} // main
}
Custom Implementation of AutoCloseable Interface:
The AutoCloseable interface is easy to implement as it just has a single method, close().
public interface AutoClosable {
public void close() throws Exception;
}
College.java
public class College implements AutoCloseable{
public College(){
System.out.println("Inside College Class");
}
public void doSomething(){
System.out.println("Doing something in College");
}
public void close() throws Exception{
System.out.println("Closed College");
}
}
Canteen.java
public class Canteen implements AutoCloseable{
public Canteen (){
System.out.println("Inside Canteen Class");
}
public void doSomething() throws Exception{
throw new Exception("Exception from Canteen doSomething() method");
}
public void close() throws Exception{
System.out.println("Closing Canteen ");
throw new Exception("Unable to close Canteen...);
}
}
TryWithResources.java
public class TryWithResources {
public static void main(String[] args){
try(College b = new College();Canteen f = new Canteen ()){
b.doSomething();
f.doSomething();
}catch(Exception ex){
System.out.println("In catch... " + ex);
}finally{
System.out.println("In finally...");
}
}
}
Explanation:
The first thing to notice here is that the order in which the resources are opened and closed.
College is opened and then Foo but while closing, reverse order is followed. Foo is closed and then College resource.
Canteen’s close() throws an exception but if you notice the generated output, it is suppressed.
Only the exception that is generated in the try block by doSomething() is thrown by the main method of MyTryWithResources
This is the main concept to understand here in try-with-resources. Let us try to distill this
information step by step, College and Canteen resources are created in the try-with-resources block.
Try block starts to execute.
The doSomething() of College class gets executed successfully and prints the message, “Doing something in College!†to console.
An exception is thrown from the doSomething() method of the Canteen class.
Before transferring the control to catch method to handle the exception, resources are closed by invoking their respective close() methods.
The close() of Canteen class prints the message, “Closing Canteen†to console and throws an
exception which gets suppressed as the exception thrown by the try block gets exposed.
This suppression of exception from try-with-resources statement happens only when both try
block and try-with-resources statement (close() method) throw exceptions. The close() of College class is run and it prints the message “Closing College†to the console.
Then finally block gets executed.
What if you want to retrieve the suppressed exceptions as well? Not to worry. In Java SE 7 and later, they can be retrieved by using getSuppressed() method.
Though an exception is thrown while closing a particular resource, all opened resources will be closed irrespective of the thrown exception. In our example, though there was an exception while closing Canteen resources, College resource was closed successfully as well.
Common Exceptions , Handling examples
Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when an integer is divided by zero.
class Example1
{
public static void main(String args[])
{
try{
System.out.println ("Result:10/0);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
Output of above program:
You Shouldn't divide a number by zero
Example 2: ArrayIndexOutOfBounds Exception
Class: Java.lang.ArrayIndexOutOfBoundsException
This exception occurs when you try to access the array index which does not exist.
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Example 3: NumberFormat Exception
Class: Java.lang.NumberFormatException
This exception occurs when a string is parsed to any numeric variable.
For example, the statement int num=Integer.parseInt ("XYZ"); would throw
NumberFormatException because String “XYZ†cannot be parsed to int.
class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output:
Number format exception occurred
Example 4: StringIndexOutOfBound Exception
Class: Java.lang.StringIndexOutOfBoundsException
An object of this class gets created whenever an index is invoked of a string, which is not in the
range.
Each character of a string object is stored in a particular index starting from 0.
To get a character present in a particular index of a string we can use a method charAt(int) of
java.lang.String where int argument is the index.
E.g.
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
13
StringIndexOutOfBoundsException
Exception occurred because the referenced index was not present in the String.
Example 5: NullPointer Exception
Class: Java.lang.NullPointer Exception
An object of this class gets created whenever a member is invoked with a “null†object.
class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..