Java - Throwable to Exception

谁都会走 提交于 2019-12-03 15:59:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!