Java - Throwable to Exception

后端 未结 5 1184
清酒与你
清酒与你 2021-02-03 20:26

I am currently using the play2 framework.

I have several classes which are throwing exceptions but play2s global onError handler uses throwable

相关标签:
5条回答
  • 2021-02-03 21:02

    You can use instanceof to check it is of NoSessionException or not.

    Example:

    if (exp instanceof NoSessionException) {
    ...
    }
    

    Assuming exp is the Throwable reference.

    0 讨论(0)
  • 2021-02-03 21:07

    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
    }
    
    0 讨论(0)
  • 2021-02-03 21:09

    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
    }
    
    0 讨论(0)
  • 2021-02-03 21:10

    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

    0 讨论(0)
  • 2021-02-03 21:17

    Throwable is a class which Exception – and consequently all subclasses thereof – subclasses. There's nothing stopping you from using instanceof on a Throwable.

    0 讨论(0)
提交回复
热议问题