问题
I am currently using the play2 framework.
I have several classes which are throwing exceptions but play2s global onError handler uses throwable instead of an exception.
for example one of my classes is throwing a NoSessionException. Can I check a throwable object if it is a NoSessionException ?
回答1:
You can use instanceof to check it is of NoSessionException or not.
Example:
if (exp instanceof NoSessionException) {
...
}
Assuming exp is the Throwable reference.
回答2:
Just make it short. We can pass Throwable to Exception constructor.
@Override
public void onError(Throwable e) {
Exception ex = new Exception(e);
}
See this Exception from Android
回答3:
Can I check a throwable object if it is a NoSessionException ?
Sure:
Throwable t = ...;
if (t instanceof NoSessionException) {
...
// If you need to use information in the exception
// you can cast it in here
}
回答4:
In addition to checking if its an instanceof you can use the try catch and catch NoSessionException
try {
// Something that throws a throwable
} catch (NoSessionException e) {
// Its a NoSessionException
} catch (Throwable t) {
// catch all other Throwables
}
回答5:
Throwable is a class which Exception – and consequently all subclasses thereof – subclasses. There's nothing stopping you from using instanceof on a Throwable.
来源:https://stackoverflow.com/questions/12359175/java-throwable-to-exception