LightBlog

Java - Exception Handling


 The unexpected unwanted event which disturbs entire flow of the program is known as “Exception”
·         If we are not handling exception, the program may terminate abnormally with out releasing allocated resources.

·         Exception handling means it is not repairing an exception, just providing alternative way to continue the program execution normally.

Common scenarios where exceptions may occur
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException 

If we have null value in any variable, performing any operation occurs a NullPointerException.
String s=null; 
System.out.println(s.length());//NullPointerException 

The wrong formatting of any value, may occur NumberFormatException.
String s="abc"; 
int i=Integer.parseInt(s);//NumberFormatException 

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException
int a[]=new int[5]; 
a[10]=50; //ArrayIndexOutOfBoundsException 


Default Exception Handling
·         When ever an exception raised, the method in which it is raised is responsible for the preparation of exception object by including the following information
Name of Exception.
Description.
Location of Exception

·         After preparation of Exception Object, the method handovers the object to the JVM, JVM will check for Exception handling code in that method.

·          If the method doesn’t contain any exception handling code then JVM terminates that method abnormally and removes corresponding entry from the stack.

·         JVM will check for exception handling code in the caller and if the caller method also doesn’t contain exception handling code then JVM terminates that caller method abnormally and removes corresponding entry from the stack.

·         This process will be continued until main method , if the main method also doesn’t contain any exception handling code then JVM terminates main method abnormally.

·         Just before terminating the program JVM handovers the responsibilities of exception handling to default exception handler.

·          Default exception handler prints the error in the following format.
Name of Exception : Description
stackTrace


Exception Hierarchy
Throwable is the parent of entire java exception hierarchy. It has 2 child classes.
  1. Exception
  2. Error.


1.Exception

These are recoverable. Most of the cases exceptions are raised due to program code only.

Checked Exceptions: They Cheeked by Compiler, the given resource is existed or not, They are usually occur interacting with outside resources/ network resources e.g. database problems, network connection errors, missing files etc. Java forces you to handle these error scenarios in some manner in your application code

Unchecked Exceptions: occurrences of which are not checked by the compiler like coding, initialization, Primitive data errors. They usually result of bad code in your system.

Runtime Exception and it’s child classes, Error and it’s child classes are considered as unchecked exceptions and all the remaining considered as checked


2.Error

Errors are non-recoverable. Most of the cases errors are due to lack of system resources but not due to our programs.
JVM +Memory+ OS level issues. OutofMemory, StatckOverFlow


Partially Checked vs Fully Checked
A checked exception is said to be fully checked iff all it’s child classes also checked.
Ex:- IOException.

A checked exception is said to be partially checked if some of it’s child classes are not checked.
Ex:- Exception, Throwable.


Number of ways to find details of the exception

1.Using an object of java.lang.Exception
try
{
int x=Integer.parseInt ("10x");
}
catch (Exception e)
{
   System.out.println (e); // java.lang.NumberFormatException : for input string 10x
}                               name of the exception       ||  nature of the message

2.Using printStackTrace method
e.printStackTrace (); // java.lang.ArithmeticException : / by zero : at line no: 4
                 name of the exception         || nature of the message || line number

3.Using getMessage method:
System.out.println (e.getMessage ()); // / by zero
                                                                nature of the message



Using try, catch, finally
·         We have to place the risky code inside the try block and the corresponding exception handling code inside catch block.
Without try-catch
With try-catch
class Test {
 public static void main(String arg[]) {
       System.out.println("Statement 1");
       System.out.println(10 / 0);
       System.out.println("Statement 2");
       }
 }
class Test {
  public static void main(String arg[])
   {
      System.out.println("Statement 1");
        try {
                System.out.println(10 / 0);
        }
        catch (ArithmeticException e)
        {
                System.out.println(10 / 2);
        }
        System.out.println("Statement 2");
   }
}
Statement 1
Exception in thread "main" java.lang.ArithmeticException: / by zero

Statement 1
5
Statement 2

·         In the case of try with multiple catch blocks the order of catch blocks is important. And it should be from child to parent, other wise Compiler Error. Saying Exception xxx has already been caught.

·         If there is no chance of raising an exception in try statement, then we are not allowed to maintain catch block for that exception violation leads to compile time error. but this rule is applicable only for fully checked exceptions.
class Test {
    public static void main(String arg[]) {
            try {
                    System.out.println("Hi");
            } catch (IOException e) {
            }
    }
}
Test.java:7: error: exception IOException is never thrown in body of corresponding try statement
                } catch (IOException e) {
                  ^

·         It is not recommended to maintain cleanup code with in the catch block. because there is no guaranty of execution of particular catch block.

·         finally block should always execute irrespective of whether the execution is raised or not raised or handled or not handled.

·         The finally block won’t be executed ,if the system it self exists(JVM shutdown) i.e in the case of  System.exit() finally block won’t be executed.

Possible combinations of try, catch, finally
try
{
}
catch (X e)
{
}
finally
{
}
CORRECT
try
{
}
finally
{
}

CORRECT
try
{
}


CE: error: 'try' without 'catch', 'finally' or resource declarations
try
{
}
System.out.println("Hello");
catch (X e)
{
}

CE: error: 'try' without 'catch', 'finally' or resource declarations
try
{
}
catch (X e)
{
}
System.out.println("Hello");
finally
{
}
CE: error: 'try' without 'catch', 'finally' or resource declarations
try
{
}
finally
{
}
catch (X e)
{
}
CE: error: 'try' without 'catch', 'finally' or resource declarations

The following program will demonstrate the control flow in different cases.
class Demo {
       public static void main(String arg[]) {

              try{                
                     statement1;
                     statement2;
                     statement3;                              

              } catch (Exception e)
              {
                     statement4;
              } finally
              {
                     statement5;
              }
              statement6;
       }
}
·         if there is no exception, then the statements 1, 2, 3, 5, 6 will execute with normal termination.

·         if an exception raised at statement-2 and the corresponding catch block matched, then the statements 1, 4, 5, 6 will execute with normal termination.

·         if an exception raised at statement-2 but the corresponding catch block not matched then the statements 1, 5, 6 will execute with abnormal termination.

·         if an exception raised at statement-2 and while executing the corresponding catch block at statement–4 an exception raised then the statements 1, 5 will execute with abnormal termination.

·         if an exception raised at statement-5 or at statement-6 then it is always abnormal condition.


Throws

If our code may be a chance of raising checked exception then compulsory we should handle that checked exception either by using try, catch or we have to delegate that responsibility to the caller using throws keyword other wise C.E : must be caught or declared to be thrown

Throws will give an indication to the calling function to keep the called function under try and catch blocks.

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
class Cal {
        public void div(String a, String b) throws ArithmeticException,NumberFormatException {
                int c = Integer.parseInt(a) / Integer.parseInt(b);
        }
}

public class A {
        public static void main(String[] args) {
                Cal ob = new Cal();
                try {
                        ob.div("a", "b");
                } catch (ArithmeticException e) {
                        System.out.println("Divide By Zero");
                } catch (NumberFormatException e) {
                        System.out.println("Enter Only INT's");
                } catch (Exception e) {
                        System.out.println(" Some Other " + e);
                }
        }
}
Enter Only INT's
In above throws ArithmeticException,NumberFormatException Indicates it may throws these exceptions so please put ob.div(str,str) method in try,catch block


Throw

Throw keyword is used to explicitly throw an exception.

In above we didn’t create any Exception class Object in throws because JVM automatically creates Objects. If you want to create Exception class object manually and throw exception using throw keyword
public class Marks {
        public void pass(int marks) {
                if (marks < 35) {
                        throw new ArithmeticException("You are Failed");
                } else {
                        System.out.println(" You are Pass : " + marks);
                }
        }
       
        public static void main(String[] args) {
                Marks m = new Marks();
                m.pass(26);
        }
}
Exception in thread "main" java.lang.ArithmeticException: You are Failed
        at excep.Marks.pass(Marks.java:9)
        at excep.Marks.main(Marks.java:18)


User Defined Exceptions
User defined exceptions are those which are developed by JAVA programmer as a part of Application development for dealing with specific problems such as negative salaries, negative ages.

3 Steps to developing user defined exceptions
1.       Choose the appropriate user defined class must extends either java.lang.Exception or java.lang.RunTimeException class.
2.       That class must contain a parameterized Constructor by taking string as a parameter.
3.       Above constructor must call super constructor with string Ex : super(s)



Example
For implementing example, we must create 3 classes
1.      User defined Exception class
2.      A class with a method which throws User defined Exception
3.      Main class which calls above method

1.User Defined Exception class รจ 1.Extends Exception || 2.Constructor(s) || 3.Super(s)
public class NegativeNumberException extends Exception {
   public NegativeNumberException(String s) {
          super(s);
   }
}

2.A class with a method which throws User defined Exception รจ throws & throw
public class Salary {
   public void show(int sal) throws NegativeNumberException {
          if (sal < 0) {
                 throw new NegativeNumberException("Salary Should be >1");
          } else {
                 System.out.println("Your Sal is :" + sal);
          }
   }
}

3.Main class which calls above method
public class UserMain {
   public static void main(String[] args) {
          Salary salary = new Salary();
          try {
                 salary.show(-100);
          } catch (NegativeNumberException e) {                   
                 e.printStackTrace();
          }
   }
}
excep.NegativeNumberException: Salary Should be >1
    at excep.Salary.show(Salary.java:8)
    at excep.Salary.main(Salary.java:18)


ExceptionHandling with MethodOverriding in Java

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.



Java 1.7 Exception handling Enhancements

Java try-with-resources

·         Before java 7, we had to use finally blocks to cleanup the resources. Finally blocks were not mandatory, but resource clean up was to prevent the system from being corrupt.
·         With java 7, no need to explicit resource cleanup. Its done automatically.
·         Automatic resource cleanup done when initializing resource in try-with-resources block (try(…) {…}).
·         Cleanup happens because of new interface AutoCloseable. Its close method is invoked by JVM as soon as try block finishes.
·         If you want to use this in custom resources, then implementing AutoCloseable interface is mandatory. otherwise program will not compile.
public class ResourceManagementInJava7 {
    public static void main(String[] args) {
            try ({
BufferedReader br = new BufferedReader(new FileReader("C:/temp/test.txt")}
)) {
                    String sCurrentLine;
                    while ((sCurrentLine = br.readLine()) != null) {
                            System.out.println(sCurrentLine);
                    }
            } catch (IOException e) {
                    e.printStackTrace();
            }
    }
}

In java 7, we have a new super interface java.lang.AutoCloseable. This interface have one method:
void close() throws Exception;
When we open any such AutoCloseable resource in special try-with-resource block, immediately after finishing the try block, JVM calls this close() method on all resources initialized in “try()” block.


Catch with Multiple Exception classes

From Java 7 onwards, you can catch multiple exceptions in single catch block using ( | ) symbol.
 catch(NullPointerException | IndexOutOfBoundsException ex)
        {
            Ex.printStackTrace();
        }
·         If a catch block handles more than one exception type, then the catchparameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

·         The Exceptions must be in same level of Hierarchy.
catch(NullPointerException | Exception ex)
        {
            throw ex;
        } The exception NullPointerException is already caught by the alternative

Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment