Thursday 25 January 2018

6.0 Exception Handling in java

Exception - It is an event - Abnormal termination of a program because of so and so reason.

Rest of the code will not run after unexpected event.

The main objective of exception handling is graceful termination of program.
Defining alternative way to complete the program normally is the concept of exception handling.
It doesn't mean repairing an exception.




To overcome the problem we use exception handling - To execute the full code without any unexpected termination


Runtime Stack mechanism
Jvm will create a runtime stack, each method will be get in the stack. Those entry are called activation record or stack frame. After completing every method call the corresponding entry from the stack will be removed .After completing all methods call the stack will become empty and that empty stack will be destroyed by JVM just before terminating the thread.

If something goes wrong

class TestRuntimeStackException                                                                         
{                                                                                                                             
public static void main(String args[])                                                            
{                                                                                                                     
TestRuntimeStackException obj=new TestRuntimeStackException();
obj.doStuff();                                                                                         
}                                                                                                                     
public void doStuff()                                                                                     
{                                                                                                                     
doMoreStuff();                                                                                       
}                                                                                                                     
public void doMoreStuff()                                                                             
{                                                                                                                     
System.out.println(10/0);                                                                       
System.out.println("Hello");                                                                  
}                                                                                                                     
}                                                                                                                             

C:\Users\Aarchi\Desktop\Java Development>javac TestRuntimeStackException.java

C:\Users\Aarchi\Desktop\Java Development>java TestRuntimeStackException
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at TestRuntimeStackException.doMoreStuff(TestRuntimeStackException.java:14)
        at TestRuntimeStackException.doStuff(TestRuntimeStackException.java:10)
        at TestRuntimeStackException.main(TestRuntimeStackException.java:6)

Inside a method if an exception occured the method in which it occurs responsible to create exception object. This method hand over this object to the JVM. 
JVM will ask In which area it happens (doMoreStuff) - Is there exception handling  ? no there is no handling code - JVM will check who is the caller of doMoreStuff. JVM will delete that method from the stack and ask doStuff - is there any handling code - doStuff is not having any handling code. JVM will terminate this method immediately and delete from stack. This method is called by main. But main is also not handled this exception. JVM will asks same questions to main method. JVM will terminate the main method abnormally and will remove the corresponding entry from stack. It is not handled by anyone ,JVM will give this responsibility to default exception handler. Default exception handler will print the exception in the console.

Exception Handling Chart


There are two ways to handle exception



  1. Try catch block
  2. Throws keyword
Type of exception
  1. unchecked
  2. checked
  3. Error

UNCHECKED EXCEPTION



class exceptionpart1
{
public static void main(String args[])
{
System.out.println("Hello world");
System.out.println("Hello world");
System.out.println(10/0);
System.out.println("Hello world");
System.out.println("Hello world");

}
}











class class exceptionpart1
{
public static void main(String args[])
{
//System.out.println(10/0);
int[] a={10,20,30,40};
System.out.println(a[0]);
System.out.println(a[10]);
System.out.println("rest of the application");

}
}





  • Code is compiled but not running and giving ArithmeticException in example 1 and ArrayIndexOutOfBoundsException in example 2.
  • The exception which are unable to check by compiler those are known as unchecked exception


CHECKED EXCEPTIONS

class exceptionpart1

{
public static void main(String args[])
{
System.out.println("Hello world");
System.out.println("Hello world");
System.out.println("Hello world");
Thread.sleep(3000); //3sec
System.out.println("Hello world");
System.out.println("Hello world");

}

}

C:\Users\Aarchi\Desktop\Java Development>javac exceptionpart1.java

exceptionpart1.java:8: error: unreported exception InterruptedException; must be caught or declared to be thrown
                Thread.sleep(3000); //3sec
                            ^
1 error

Thread.sleep(3000) - thread is going into sleep and other threads can  interrupt which can cause abnormal termination of the code therefore compiler conveying information to developer that use try catch.


  • The exceptions which are checked by compiler are called checked exception.
  • The code will not compile
  • The exception which are checked by compiler for smooth execution of the program at run time is known as checked exception.
NOTE : Exception occurs only at run time whether it is checked or unchecked


TO PRINT EXCEPTION DETAILS


If try with multiple catch blocks are present then order of catch block is very important.
We have to take child first and then parent otherwise we will get compile error saying
exception xxx has already been caught.
Final Finally Finalize

IMPORTANT POINTS ABOUT TRY CATCH AND FINALLY

  1. In try catch finally order is important.
  2. try without catch or finally is invalid
  3. try catch or try finally is fine
  4. try finally catch is invalid
  5. try finally catch - curly braces is must.
  6. try catch in try or catch or finally block is valid.

THROW and THROWS

Sometimes we can create exception object explicitly and we can handover to the JVM manually, for this we have to use THROW keyword.

throw new ArithmeticException("/ by zero ");

Throw keyword is use to handover our created exception object to the jvm manually.

best use of throw is use to throw user defined exceptions.
Example 
widraw=20000
if (ballance < 10000)
throw new InsuffeciantFundException("Low balance");


CASE 1 :


class expcase1
{
static ArithmeticException e=new ArithmeticException();
public static void main(String args[])
{
throw e;
}
}

C:\Users\Aarchi\Desktop\Java Development>javac expcase1.java

C:\Users\Aarchi\Desktop\Java Development>java expcase1
Exception in thread "main" java.lang.ArithmeticException
        at expcase1.<clinit>(expcase1.java:3)


class expcase1
{
static ArithmeticException e;
public static void main(String args[])
{
throw e;
}
}

C:\Users\Aarchi\Desktop\Java Development>javac expcase1.java

C:\Users\Aarchi\Desktop\Java Development>java expcase1
Exception in thread "main" java.lang.NullPointerException
        at expcase1.main(expcase1.java:6)



CASE 2 :  you can't write any code immediately  after throw statement because compiler already now that exception throwing will terminate the program and the next line will be unreachable. You'll get compile time error.

class expcase1
{
public static void main(String args[])
{
System.out.println(10/0);
System.out.println("Hello World");
}

}


C:\Users\Aarchi\Desktop\Java Development>javac expcase1.java

C:\Users\Aarchi\Desktop\Java Development>java expcase1
Exception in thread "main" java.lang.NullPointerException
        at expcase1.main(expcase1.java:6)


class expcase1
{
public static void main(String args[])
{
throw new ArithmeticException("/ by zero");
System.out.println("Hello World");
}
}

C:\Users\Aarchi\Desktop\Java Development>javac expcase1.java
expcase1.java:6: error: unreachable statement
                System.out.println("Hello World");
                ^
1 error


CASE 3 : throw is only use for throwable type object not any other java object.
It will give you java.lang.throwable

class test
{
public static void main(String args[])
{
throw new test();
}
}

C:\Users\Aarchi\Desktop\Java Development>javac test.java
test.java:5: error: incompatible types: test cannot be converted to Throwable
                throw new test();
                ^
1 error

class test extends RuntimeException // now it is throwable
{
public static void main(String args[])
{
throw new test();
}
}

C:\Users\Aarchi\Desktop\Java Development>javac test.java

C:\Users\Aarchi\Desktop\Java Development>java test
Exception in thread "main" test
        at test.main(test.java:5)


THROWS - In our program if there is possibility of raising checked exception then compulsory we should handle that checked exception otherwise we'll get compile time error saying "unreported exception xxx must be caught or declared to be thrown.

import java.io.*;
class test
{
public static void main(String args[])
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.write("Hello");
}
}

C:\Users\Aarchi\Desktop\Java Development>javac test.java
test.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
                PrintWriter pw=new PrintWriter("abc.txt");
                               ^
1 error


class test
{
public static void main(String args[])
{
Thread.sleep(10000);
}
}

C:\Users\Aarchi\Desktop\Java Development>javac test.java
test.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown
                Thread.sleep(10000);
                            ^
1 error

we can handle these compile time error  by using following two ways.

  1. By using try catch block
  2. By using throws keyword
we can use throws keyword to delegate responsibility of exception handling to the caller (It may be another method or JVM) then caller method is responsible to handle that exception.

public static void main(String args[]) throws InterruptedException
  • Throws keyword required only for checked exceptions .
  • Throws keyword only requires to convince the compiler and usage of throws keyword doesn't prevent abnormal termination of the program.
  • throws keyword we can only use with method,constructor not with class.
  • We can use throws keyword only for throwable types. If we will try to use it for normal java classes then we will get compile time error saying "incompatible types
DIFFERENT LEVEL OF DELEGATION


class test
{
public static void main(String args[]) throws InterruptedException
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
Thread.sleep(1000);
}

}


C:\Users\Aarchi\Desktop\Java Development>javac test.java
test.java:13: error: unreported exception InterruptedException; must be caught or declared to be thrown
                Thread.sleep(1000);
                            ^
1 error

class test
{
public static void main(String args[]) 
{
doStuff();
}
public static void doStuff() 
{
doMoreStuff();
}
public static void doMoreStuff() throws InterruptedException
{
Thread.sleep(1000);
}
}

C:\Users\Aarchi\Desktop\Java Development>javac test.java
test.java:9: error: unreported exception InterruptedException; must be caught or declared to be thrown
                doMoreStuff();
                           ^
1 error


class test
{
public static void main(String args[]) 
{
doStuff();
}
public static void doStuff() throws InterruptedException
{
doMoreStuff();
}
public static void doMoreStuff() throws InterruptedException
{
Thread.sleep(1000);
}
}

C:\Users\Aarchi\Desktop\Java Development>javac test.java
test.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown
                doStuff();
                       ^
1 error


class test
{
public static void main(String args[]) throws InterruptedException
{
doStuff();
}
public static void doStuff() throws InterruptedException
{
doMoreStuff();
}
public static void doMoreStuff() throws InterruptedException
{
Thread.sleep(1000);
}
}

C:\Users\Aarchi\Desktop\Java Development>javac test.java

C:\Users\Aarchi\Desktop\Java Development>java test

C:\Users\Aarchi\Desktop\Java Development>


DoMoreStuff is not delegating the exception to main below

class test
{
public static void main(String args[]) throws InterruptedException
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff() 
{
Thread.sleep(1000);
}

}

C:\Users\Aarchi\Desktop\Java Development>javac test.java
test.java:13: error: unreported exception InterruptedException; must be caught or declared to be thrown
                Thread.sleep(1000);
                            ^

1 error


THROWS - In our program if there is possibility of raising checked exception then compulsory we should handle that checked exception otherwise we'll get compile time error saying "unreported exception xxx must be caught or declared to be thrown.




FULLY CHECKED EXCEPTION - 






















List of compile time errors


  1. unreported exception InterruptedException; must be caught or declared to be thrown
  2. Exception xxx has already been caught
  3. Exception xxx is never thrown in boy of corresponding try statement.
  4. Unreachable statements
  5. incompatible types
  6. try without catch or finally
  7. catch without try
  8. finally without try.
Customized or User defined Exceptions
Sometimes to meet programming requirements we can define our own exceptions such types of exceptions are called Customized or user defined exceptions.

It is highly recommended to define our customized exceptions as unchecked i.e we have to extend runtimeException but not Exception.


class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}  

class TestCustomException1{  
  
   static void validate(int age)throws InvalidAgeException{  
     if(age<18)  
      throw new InvalidAgeException("not valid");  
     else  
      System.out.println("welcome to vote");  
   }  
     
   public static void main(String args[]){  
      try{  
      validate(13);  
      }catch(Exception m){System.out.println("Exception occured: "+m);}  
  
      System.out.println("rest of the code...");  
  }  
}  

No comments:

Post a Comment