Wednesday, 26 February 2014

Throwable Constructors

1. public Throwable() : Constructs a new throwable object
Example
public class ThrowableEx {
 static void print()throws Throwable{
  try{
   int a = 10/0;
  }
  catch(ArithmeticException e){
   Throwable t1 = new Throwable();
   t1.initCause(e);
   throw t1;
  }
 }

 public static void main(String args[]){
  Throwable t1 = new Throwable();
  try{
   print();
  }
  catch(Throwable t){
   System.out.println("Exception \t\t Cause");
   System.out.println(t + "\t" + t.getCause());
  }
 }
}

 Output
Exception Cause
java.lang.Throwable java.lang.ArithmeticException: / by zero
   
Suppose error e1, throws another exception e2, then e1 is the cause for e2.

2. public Throwable(String message)
Constructs a new throwable with the specified detail message.

public class ThrowableEx {
 static void print()throws Throwable{
  try{
   int a = 10/0;
  }
  catch(ArithmeticException e){
   Throwable t1 = new Throwable("Divide by zero exception");
   throw t1;
  }
 }

 public static void main(String args[]){
  Throwable t1 = new Throwable();
   try{
    print();
   }
   catch(Throwable t){
    System.out.println(t);
   }
 }
}

Output
 java.lang.Throwable: Divide by zero exception
   

3. public Throwable(String message, Throwable cause)
Constructs a new throwable with the specified detail message and cause.
public class ThrowableEx {
 static void print()throws Throwable{
  try{
   int a = 10/0;
  }
  catch(ArithmeticException e){
   Throwable t1 = new Throwable("Divide by zero exception", e);
   throw t1;
  }
 }

 public static void main(String args[]){
  Throwable t1 = new Throwable();
  try{
   print();
  }
  catch(Throwable t){
   System.out.println(t.getMessage() +"\t" + t.getCause());
  }
 }
}

Output
Divide by zero exception java.lang.ArithmeticException: / by zero


4. public Throwable(Throwable cause)
Constructs a new throwable with the specified cause

public class ThrowableEx {
 static void print()throws Throwable{
  try{
   int a = 10/0;
  }
  catch(ArithmeticException e){
   Throwable t1 = new Throwable(e);
   throw t1;
  }
 }

 public static void main(String args[]){
  Throwable t1 = new Throwable();
  try{
   print();
  }
  catch(Throwable t){
   System.out.println(t);
  }
 }
}

Output
java.lang.Throwable: java.lang.ArithmeticException: / by zero
  
   


Throwable class                                                 Stack trace                                                 Home

No comments:

Post a Comment