Thursday, 27 February 2014

checked vs unchecked Exceptions

1. Checked exceptions are those which are checked at compile time, Unchecked exceptions are not checked at compile time and raised at run time.

2. In Java, Error, RuntimeExceptions and its subclasses comes under unchecked exceptions category, where as Exception and its sub classes comes under checked exceptions category.

3. Checked exceptions are subject to catch/specify requirement.

For Example, see the below program,

import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name ");
  String name = br.readLine();
  System.out.println("Hi " + name);
 }
}
   
br.readLine(), throws IOException, which is a checked exception, so compiler checks whether the program handles it or not, If the program is not handling then compiler throws the error. Above program is not handling the cecked Exception (IOException), so compiler throws the below error.

CheckedEx.java:7: error: unreported exception IOException; must be caught or declared to be thrown
String name = br.readLine();
^
1 error

To make the program compile and runs fine, There are two options

Option 1: program can handle the IOException.
import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  try{
   System.out.println("Enter your name ");
   String name = br.readLine();
   System.out.println("Hi " + name);
  }
  catch(IOException e){
   System.out.println(e);
  }
 }
}

Output
Enter your name
abc
Hi abc

Option 2: program can throws the IOException.
import java.io.*;

class CheckedEx{
 public static void main(String args[]) throws IOException{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name ");
  String name = br.readLine();
  System.out.println("Hi " + name);
 }
}

Output
Enter your name
abc
Hi abc

4. Program can handle and recover from checked exceptions, Of course from RuntimeException recovery is possible. Error are special category of unchecked exception, Where recovery from them is almost impossible.

5. Compiler throws an error, if the program tries to handle a checked exception, which will never occurs in the program.

import java.io.*;

class CheckedEx{
 public static void main(String args[]){
  try{
   int a = 10+20;
  }
  catch(IOException e){
  
  }
 }
}

When you tries to compile the above program, compiler throws the below error

CheckedEx.java:7: error: exception IOException is never thrown in body of corresponding try statement
catch(IOException e){
^
1 error

Custom Exceptions                                                 Overriding vs Exception Handling                                                 Home

How to create user defined exceptions

You can create user defined exception by simply extending the Exception class.

Example
class MyException extends Exception{
 MyException(String msg){
  super(msg);
 }
}
    
class MyExceptionTest{
 static void print(int val)throws Exception{
  if(val < 0 ){
   throw new MyException("Values is less than zero:" + val);
  }
  else{
   System.out.println(val);
  }
 }

 public static void main(String args[]){
  try{
   print(-10);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}
   
Output
MyException: Values is less than zero:-10
  
In the same way we can create RuntimeExceptions by extending the RuntimeException class.


Chained Exceptions                                                 checked vs unchecked exceptions                                                 Home

Chained Exceptions: getCause, initCause

One exception causes to throw other Exception is called chained Exception. Exception chaining is also called nesting exceptions. Some times it is good to know, what is the cause for this exception.

Throwable class support two methods to support chained exceptions.

Initialize the cause for an Exception
public Throwable initCause(Throwable cause)
Initializes the cause of this throwable to the specified value.
   Ex:
   exce1.initCause(exce2)'

Here the exception exce2 is the cause for the exception exce1.

Get the cause for an Exception
public Throwable getCause()
Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Example
class CauseEx{
 static void divide(){
  try{
   int a = 10/0;
  }
  catch(ArithmeticException e){
   try{
    int a[] = new int[10];
    a[11] = 100;
   }
   catch(Exception e1){
    e1.initCause(e);
    throw e1;
   }
  }
 }

 public static void main(String args[]){
  try{
   divide();
  }
  catch(Exception e){
   System.out.println(e);
   System.out.println("Cause for this exception is " + e.getCause());
  }
 }
}
   
Output
java.lang.ArrayIndexOutOfBoundsException: 11
Cause for this exception is java.lang.ArithmeticException: / by zero
  

Throwable class supports two constructors for chained exceptions handling.

1. Throwable(Throwable cause)
Constructs a new throwable with the specified cause and a detail message.

2. Throwable(String message, Throwable cause)
Constructs a new throwable with the specified detail message and cause.

Some Points to remember

1. InitCause() called at most once. Calling this more than once cause "IllegalStateException".

Example
class CauseEx{
 static void divide(){
  try{
   int a = 10/0;
  }
  catch(ArithmeticException e){
   try{
    int a[] = new int[10];
    a[11] = 100;
   }
   catch(Exception e1){
    e1.initCause(e);
    e1.initCause(e);
    throw e1;
   }
  }
 }

 public static void main(String args[]){
  try{
   divide();
  }
  catch(Exception e){
   System.out.println(e);
   System.out.println("Cause for this exception is " + e.getCause());
  }
 }
}

Program compiles fine, But at run time below error is thrown, since initCause called twice on the same Throwable object.
      
java.lang.IllegalStateException: Can't overwrite cause
Cause for this exception is null

2. A throwable can't be cause for itself.
Example
class CauseEx{
 static void divide(){
  try{
   int a = 10/0;
  }
  catch(ArithmeticException e){
   try{
    int a[] = new int[10];
    a[11] = 100;
   }
   catch(Exception e1){
    e1.initCause(e1);
    throw e1;
   }
  }
 }

 public static void main(String args[]){
  try{
   divide();
  }
  catch(Exception e){
   System.out.println(e);
   System.out.println("Cause for this exception is " + e.getCause());
  }
 }
}

Program compiles fine, But at run time "IllegalArgumentException" thrown, Since "e1.initCause(e1)" e1 is the cause for e1, which is wrong, Throwable can't be the cause for same Throwable.

java.lang.IllegalArgumentException: Self-causation not permitted
Cause for this exception is null


3. Constructors like “Throwable(Throwable cause)”, “Throwable(String message, Throwable cause)” are initializing the cause for an exception at the time of creation of Throwable object. So Don't call the initCause() again, since it is already called.



Fill stack trace                                                 Custom Exceptions                                                 Home

Wednesday, 26 February 2014

Fill Stack Trace: fillInStackTrace

public Throwable fillInStackTrace()
Fills in the execution stack trace. This method replaces original stack trace with that from the place it is called.

Example: Before adding a call to fillInStacktrace
class StackTraceEx{
 void divide(){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   throw e;
  }
 }

 void show(){
  divide();
 }

 void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();
  try{
   obj.print();
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
}

 Output
java.lang.ArithmeticException: / by zero
  at StackTraceEx.divide(StackTraceEx.java:5)
  at StackTraceEx.show(StackTraceEx.java:12)
  at StackTraceEx.print(StackTraceEx.java:15)
  at StackTraceEx.main(StackTraceEx.java:20)
  
After adding a call to fillInStacktrace
class StackTraceEx{
 void divide(){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   throw e;
  }
 }

 void show(){
  divide();
 }

 void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();
  try{
   obj.print();
  }
  catch(Exception e){
   e.fillInStackTrace();
   e.printStackTrace();
  }
 }
}

Output
java.lang.ArithmeticException: / by zero
        at StackTraceEx.main(StackTraceEx.java:23)

After calling the method “ fillInStackTrace” The stack trace is replaced by the current stack frame.



Get stack trace                                                 Chained Exceptions                                                 Home

Get the stack trace : getStackTrace()

public StackTraceElement[] getStackTrace()
Returns an array of stack trace elements, each representing one stack frame. The zeroth element in the Array represents the top of the stack frame, for ex, where the error occurred, The last element in the Array represents the start frame of the Execution.

Example
class StackTraceEx{
 void divide(){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   throw e;
  }
 }

 void show(){
  divide();
 }

 void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();
  
  try{
   obj.print();
  }
  catch(Exception e){
   System.out.print(e + " Occurred in the method ");
   StackTraceElement[] trace = e.getStackTrace();
   for(int i=0; i < trace.length-1; i++)
    System.out.print(trace[i].getMethodName() +" Called by method ");
    System.out.print(trace[trace.length-1].getMethodName() +" in the class " + trace[trace.length-1].getClassName());
  }
 }
}

Output
java.lang.ArithmeticException: / by zero Occurred in the method divide Called by
 method show Called by method print Called by method main in the class StackTrac
eEx

StackTraceElement represents a single stack frame. It provides various utility methods to extract method name , line number, class name etc., from the stack frame.


print stack trace                                                 Fill stack trace                                                 Home

Printing Stack traces : printStackTrace

Throwable class provides printStackTrace method to get the stack trace information for a Throwable object. The Throwable object may be an error or Exception.

public void printStackTrace()
Prints this throwable and its backtrace to the standard error stream. PrintStackTrace() has two other forms also like printStackTrace(PrintStream s), printStackTrace(PrintWriter s). One for to write trace to a print stream,and other for to a print writer.

The implementation of printStackTrace (), looks like below. It is simply calling the overloaded method printStackTrace(PrintStream s) by passing System.err as an argument.

public void printStackTrace() {
      printStackTrace(System.err);
}
  
Example
class StackTraceEx{

 void divide(){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   throw e;
  }
 }

 void show(){
  divide();
 }

 void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();
  try{
   obj.print();
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
}
  

Output
java.lang.ArithmeticException: / by zero
            at StackTraceEx.divide(StackTraceEx.java:5)
            at StackTraceEx.show(StackTraceEx.java:12)
            at StackTraceEx.print(StackTraceEx.java:15)
            at StackTraceEx.main(StackTraceEx.java:20)
 
Other Overloaded methods
public void printStackTrace(PrintStream s)
Prints this throwable and its backtrace to the specified print stream.

public void printStackTrace(PrintWriter s)
Prints this throwable and its backtrace to the specified print writer.


Stack trace                                                 Get stack trace                                                 Home

What is a stack trace

A stack trace is a report of all method calls at a particular point of time during the execution of a program. Whenever an error / exception encountered in a program, then by default JVM generates the stack trace.

Example
class StackTraceEx{
 void divide(){
  System.out.println(10/0);
 }

 void show(){
  System.out.println("in show, about call divide ");
  divide();
 }

 void print(){
  System.out.println("in print, about call show ");
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();
  obj.print();
 }
}
    

Output
in print, about call show
in show, about call divide
Exception in thread "main" java.lang.ArithmeticException: / by zero
  at StackTraceEx.divide(StackTraceEx.java:4)
  at StackTraceEx.show(StackTraceEx.java:8)
  at StackTraceEx.print(StackTraceEx.java:12)
  at StackTraceEx.main(StackTraceEx.java:16)
   
Observe the below statements

Exception in thread "main" java.lang.ArithmeticException: / by zero
                                      at StackTraceEx.divide(StackTraceEx.java:4)
                             at StackTraceEx.show(StackTraceEx.java:8)
                             at StackTraceEx.print(StackTraceEx.java:12)
                             at StackTraceEx.main(StackTraceEx.java:16)

initially main method is called, main calls print, print calls show, show calls divide. “divide(StackTraceEx.java:4)” statements tells that inside divide method the ArithmeticException arises. StackTraceEx.java:4 tells that exception occurred at line number 4. So using stack trace, We can easily debug the Application.

Throwable constructors                                                 print stack trace                                                 Home