Tuesday, January 19, 2010

Exception Utility

In JAVA, Throwable/Exception thrown for many reasons. Based on its impact to the application, Throwable category is splitted into two - Exception, Error.

  • java.lang.Exception indicates that malfunction happened, and possible to correct it using try-catch block.
    • Checked Exception must to be captured in try-catch block to succeed compilation
    • UnChecked Exception need not to be captured in try-catch block to get successful compilation. These exceptions are having java.lang.RuntimeException as super class. Examples, java.lang.IllegalArgumentException, java.lang.ArrayIndexOutOfBoundsException. If we feel JVM may throw this RuntimeException then we may need to use try-catch block to capture it. Java compiler will not enforce us to use try-catch block for unchecked exception. It is developer responsibility to catch this exception, and run resolving code.
  • java.lang.Error indicates that serious problem happened which adviced not to capture using try-catch block.

Cause in Exception

In a method, Exception captured using try-catch block and thrown back to the caller method with reconstructing using some other Exception class. For instance, we got some unknown/unexpected exception in a API, which will be used to create instance of caller understandable Exception and send back to them. While reconstructing, Exception catched will be treated as cause in constructed/new Exception.

Here, very first occuring exception is called Actual Cause. Rest are just used to convey the issue to the root of the caller, where we decide alternate for this issue.

We have to know, how the issue throwing API reached from root?. This will be done by traversing stack trace of Thread from the issue araised line of code. Throwable.printStackTrace() used to get the stack trace of complete Exception and Cause. Actual cause will be displayed in end of the trace. If reconstrcution happened in various layer on the Exception then we will get equal number of Cause trace, which may annoy our customer, even developer.

We have to take a call on this and provide only the issue and trace of the same to Customer/log file. Pushing all the Cause trace, impacts peformance in multi-threaded environment, where we do log variety of details to console/Log file parallely, where as console/Log stream is synchronized which blocks/waits for other thread to relase the lock. Pushing minimal and adequate data increase the performance of application.


Exception Util

In the following sample program, APIs are exposed - getCause(), exceptionToString(),printActualCause().

  • getCause() - helps to retrieve actual cause from Exception
  • exceptionToString() - helps to retrieve stacktrace information as a String object
  • printActualCause() - prints the stacktrace, message of actual cause


import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

public class ExceptionUtil {
/**
 * get Actual cause from the exception thrown
 * 
 * @param throwable
 * @return
 */
public static Throwable getCause(Throwable throwable) {
 if (null == throwable)
  return null;
 Throwable cause = getCause(throwable.getCause());
 if (null == cause)
  cause = throwable;
return cause;
}

/** Converts stacktrace to string
 * @param t
 * @return
 */
private static String exceptionToString(Throwable t) {
String stackTrace = null;
OutputStream os = null;
try {
 os = new ByteArrayOutputStream();
 PrintWriter printWriter = new PrintWriter(os);
 t.printStackTrace(printWriter);
 printWriter.close();
 stackTrace = os.toString();
} catch (Exception exc) {
} finally {
 try {
 os.close();
 } catch (Exception e) {
 //do nothing
 }
}
return stackTrace;
}

public static void printActualCause(Throwable throwable)
{
 Throwable cause=getCause(throwable);
 String stack= exceptionToString(cause);
 String msg=cause.getLocalizedMessage();

 System.out.println(msg+"\n"+stack);
}

public static void main(String[] args) {
try
{
 throw new IllegalArgumentException("Actual exception");
}catch(Exception e)
{
 try
 {
  throw new Exception(e);
 }catch(Exception e1)
 {
  printActualCause(e1);
 }
}
} }

Reactions:

0 comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More