I'm developing a J2ME Application and I want to make a good practice for Exception Handling, I'm throwing some exceptions like
ConnectionNotFoundException, IOException, XmlPullParserException, OutOfMemory, Exception
I don't want to catch all these exception in each method that I make
so I think that I can make a new class
and this class will handle all others
I have made this class
public class ExceptionHandler extends Exception {
private Exception thrownException;
public ExceptionHandler(Exception thrownExc) {
this.thrownException = thrownExc;
if (thrownException.getClass().isInstance(ConnectionNotFoundException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(IOException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(XmlPullParserException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(NullPointerException.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(OutOfMemoryError.class)) {
// DO SOMETHING
} else if (thrownException.getClass().isInstance(Exception.class)) {
// DO SOMETHING
}
}
}
but I don't know if that is a good way or not and also I have error when I replace the thrown exceptions with mine
so what can I do please ?
You are on the right track, that is the best way to handle errors. You can also pass a second argument called message in your custom exception class and then display message here itself. Something like this:
if (thrownException.getClass().isInstance(ConnectionNotFoundException.class)) {
Dialog.alert(msg);
}
Also from the calling class, you just callnew ExceptionHandler(exception, Constants.msg)
The Constants.java class will hold all the error messages.