tags:

views:

17

answers:

1

In Java SE it is possible set the cause of an exception using initCause to avoid losing information about the error when catching and rethrowing an exception. Is it possible to do the same in Java ME?

A: 

It is easy to extend the Exception class to achieve this:

public class OperationFailedException extends Exception{
    public Exception cause;
    public OperationFailedException(String string, Exception ex) {
        super(string);
        cause=ex;
    }

    public void printStackTrace(){
        super.printStackTrace();
        System.err.println("\nCaused by:\n");
        cause.printStackTrace();
    }
}

This exception is useful for hiding the underlying exceptions, such as when we want to avoid dependancies or when we want to avoid forcing the caller to deal with too many types of exceptions. I generally also create a version of this class extending RuntimeException for wrapping exception that I want to be unchecked

Casebash