开发者

Switch Error Codes

How do I create an error handler in Android. In .Net I would simply create a handler the switch the error codes to relay the correct response required to the user.

In this case I am using a SAX parser surrounded by try and catch, when an error is raised I obviously get a message but no unique error ID. there may be ten errors captured by the try\catch block but how do I distinguish between the errors so I can try and handle the expected errors?

Ideally something like this:

switch (e.getErrorID){
case 1000:
   //Handle This Expected Error
break;
case 1064:
    //Handle This Expected Error
break;
case 2025:
    //Ha开发者_Python百科ndle This Expected Error
break;
default:
    //Unexpexted Error
}

Maybe I should mention, the error im trying to catch is empty document


Jay Dee,

In Java its typically frowned upon to have a generic exception handler. This link provides a good explanation: http://source.android.com/source/code-style.html#dont-catch-generic-exception

You'll want to do something more like...

try {
        //stuff
} catch (NumberFormatException e) {
        //specific handling for NumberFormatException
} catch (NullPointerException e) {
        //specific handling for NullPointerException 
}


Can you use multiple catch blocks in your code?

try {
// code
}catch(error1 e){
//error1 handling code
}catch(error2 e){
//error2 handling
}

and so on.


You could throw specific exceptions (possibly all extending a common base exception) and handle each in its own catch block.

You could alternatively implement a single generic exception with a getErrorCode method on which you could switch in a single catch block. (BTW this is the approach used in SQLException).

Specific exception approach:

throw new MissingAttributeException("a_mandatory_attr");
throw new InvalidAttributeValueException("some_attr", badValue);

or generic approach:

throw new GenericParsingException(MISSING_ATTRIBUTE, "a_mandatory_attr");
throw new GenericParsingException(INVALID_ATTRIBUTE_VALUE, "some_attr", badValue);

You probably find that it may be easier to throw and handle specific exceptions. This makes it easy to construct with and access different content.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜