Showing posts with label Throwable. Show all posts
Showing posts with label Throwable. Show all posts

Friday, 8 March 2019

Java: Convert throwable to string


    public static String getString(Throwable t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        return sw.toString();

    }

You may like

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

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

exception hierarchy

Exception Hierarchy


Throwable is the super class for all the exceptions in Java. Error, Exception are the two direct known subclasses for the Throwable class.

Error is a subclass of the Throwable, where a program can't handle. Exception is a sub class of the class Throwable, where program can handle.

Examples of Errors are

VirtualMachineError, InternalError, OutOfMemoryError, StackOverflowError.

Suppose if your program using the maximum heap and unable to allocate memory for new object, then OutOfMemoryError occurs. Definitely, your program can't handle the error.


java7 support for suppressed exceptions                                                 error vs exception                                                 Home

Monday, 24 February 2014

Java7 Support for Suppressed Exceptions

Throwable class provides one constructor and 2 methods to handle suppressed exceptions.

Constructor
protected Throwable( String message,
                                             Throwable cause,
                                 boolean enableSuppression,
                                 boolean writableStackTrace)

Constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled. If suppression is disabled, getSuppressed() for this object will return a zero-length array and calls to addSuppressed(java.lang.Throwable)

Will discuss about the two methods which are used to find out the suppressed Exception details.

public final void addSuppressed(Throwable exception)
Appends the specified exception to the exceptions that were suppressed in order to deliver this exception. Since this method is final, so it can't be overridden. The suppression behavior is enabled by default. If you want to disable the suppression behavior, make the flag enableSuppression to false in the above constructor.

public final Throwable[] getSuppressed()
Returns an array containing all of the exceptions that were suppressed.

import java.io.*;

class MyResource{
 String name;

 void exception1(){
  throw new RuntimeException("I am exception 1");
 } 

 void exception2(){
  throw new RuntimeException("I am exception 2");
 } 

 void exception3(){
  throw new RuntimeException("I am exception 3");
 } 

 void exception4(){
  throw new RuntimeException("I am exception 4");
 }
}
  

import java.io.*;

class SuppressEx{

 static Throwable suppressed = new Throwable();

 static MyResource obj1 = new MyResource();

 static void throwFirst(){
  try{
   obj1.exception1();
  }
  catch(Exception e){
   suppressed.addSuppressed(e);
   throwSecond();
  }
 }

 static void throwSecond(){
  try{
   obj1.exception2();
  }
  catch(Exception e){
   suppressed.addSuppressed(e);
   throwThird();
  }
 }

 static void throwThird(){

  try{
   obj1.exception3();
  }
  catch(Exception e){
   suppressed.addSuppressed(e);
   obj1.exception4();
  }
 }

 public static void main(String args[])throws Exception{
  try{
   throwFirst();
  }
  catch(Exception e){
   System.out.println(e);
  }

  System.out.println("--------------------------");
  System.out.println("Suppressed Exceptions are");
  System.out.println("--------------------------");

  Throwable[] suppressedExceptions = suppressed.getSuppressed();

  for(int i=0; i < suppressedExceptions.length; i++){
   System.out.println(suppressedExceptions[i]);
  }
 }
}

Output
java.lang.RuntimeException: I am exception 4
--------------------------------
Suppressed Exceptions are
--------------------------------
java.lang.RuntimeException: I am exception 1
java.lang.RuntimeException: I am exception 2
java.lang.RuntimeException: I am exception 3



Suppressed Exceptions                                                 Exception Hierarchy                                                 Home

using throw : Specifying the Exceptions Thrown in a Method

throw statement is used to throw an exception inside a method.

Syntax
    throw ExceptionObject;

ExceptionObject is the any subclass of the class Throwable. Since Throwable is the super class for all the exceptions in java.

Example
class Stack{
 int size;
 
 Stack(int size){
  if(size < 0 )
   throw new NegativeArraySizeException("Stack size is less than zero");
  if(size == 0)
   throw new NegativeArraySizeException("Stack size is zero");
  this.size = size;
  System.out.println("Stack created with size " + size);
 }
}
   
class StackTest{
 public static void main(String args[]){
  Stack s1;
  
  try{
   s1 = new Stack(-10);
  }
  catch(Exception e){
   System.out.println(e);
  }
  
  try{
   s1 = new Stack(0);
  }
  catch(Exception e){
   System.out.println(e);
  }
  
  try{
   s1 = new Stack(10);
  }
  catch(Exception e){
   System.out.println(e);
  }
  
 }
}

Output
java.lang.NegativeArraySizeException: Stack size is less than zero
java.lang.NegativeArraySizeException: Stack size is zero
Stack created with size 10

Program, Stack.java has a single parameterized constructor, constructor checks for the size value, before initializing the size variable, if size is less than or equal to zero, then constructor, throw the exceptions with proper messages by using throw clause. StackTest.java tested the various scenarios.

throws clause                                                 throw Vs throws                                                 Home