Tuesday 25 February 2014

Throwable class

Throwable is the super class for all the errors and Exceptions.

Only the objects of Throwable and its subclasses can be thrown by JVM or throw statement. Catch can able to catch any object which is a sub class of Throwable. So we can catch errors and RuntimeExceptions also.

The classes RuntimeException, Error and its subclasses are called as unchecked exceptions, since these are not checked at compile time. All other classes including Throwable are called checked Exceptions, since these are checked at compile time.

Checked Exceptions must be thrown or handled in the program, other wise program won't compile.

class CheckedEx extends Throwable{
 CheckedEx(String s){
  super(s);
 }

 CheckedEx(){

 }

 void print()throws CheckedEx{
  throw new CheckedEx("I am checked Exception");
 }
}
   
CheckedEx extending the class Throwable, So it is a checked exception. So it must be handled or thrown.

class ThrowableEx{
 public static void main(String args[]){
  CheckedEx obj = new CheckedEx();
  obj.print();
 }
}
   
When you tries to compile the above prgram, compiler thrws below error. Since checked exception is not handled or thrown.

ThrowableEx.java:4: error: unreported exception CheckedEx; must be caught or declared to be thrown
obj.print();
^
1 error

To make the program compiles fine, we have two options.

Option 1 : Throw the exception
class ThrowableEx{
 public static void main(String args[])throws Throwable{
  CheckedEx obj = new CheckedEx();
  obj.print();
 }
}


Output
Exception in thread "main" CheckedEx: I am checked Exception
 at CheckedEx.print(CheckedEx.java:12)
 at ThrowableEx.main(ThrowableEx.java:4)
 
Option 2: Handle the exception using catch
class ThrowableEx{
 public static void main(String args[]){
  CheckedEx obj = new CheckedEx();
  try{
   obj.print();
  }
  catch(CheckedEx e){
   System.out.println("Exception occured " + e);
  }
 }
}


Output
 Exception occured CheckedEx: I am checked Exception


A Throwable object contains the information about the stack trace, at the time it was created.

Example
class ThrowableEx{
 public static void main(String args[]){
  CheckedEx obj = new CheckedEx();
  try{
   obj.print();
  }
  catch(CheckedEx e){
   System.out.println("Stack trace is ");
   e.printStackTrace(System.out);
  }
 }
}
   
Output
Stack trace is
CheckedEx: I am checked Exception
 at CheckedEx.print(CheckedEx.java:12)
 at ThrowableEx.main(ThrowableEx.java:5)
    


error vs exception                                                 Throwable constructors                                                 Home

No comments:

Post a Comment