如何检查Java中抛出了哪种异常类型?

jea*_*ean 21 java exception-handling

如果操作捕获多个异常,如何确定捕获的异常类型?

这个例子应该更有意义:

try {
  int x = doSomething();
} catch (NotAnInt | ParseError e) {
  if (/* thrown error is NotAnInt */) {    // line 5
    // printSomething
  } else {
    // print something else
  }
}
Run Code Online (Sandbox Code Playgroud)

在第5行,我如何检查捕获的异常?

我试过if (e.equals(NotAnInt.class)) {..}但没有运气.

注意:NotAnInt并且ParseError我的项目中的类是扩展的Exception.

Eri*_*lun 38

如果您不能将这两个案例放在单独的catch块中,请使用:

} catch (NotAnInt e) {
    // handle NotAnInt
} catch (ParseError e) {
    // handle ParseError
}
Run Code Online (Sandbox Code Playgroud)

这有时是合理的,就像你需要两个或更多不同异常类的共享逻辑一样.

否则,使用单独的if块:

} catch (NotAnInt | ParseError e) {
    // a step or two in common to both cases
    if (e instanceof NotAnInt) {
        // handle NotAnInt
    } else  {
        // handle ParseError
    }
    // potentially another step or two in common to both cases
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ola 11

使用多个catch块,每个例外一个:

try {
   int x = doSomething();
}
catch (NotAnInt e) {
    // print something
}
catch (ParseError e){
    // print something else
}
Run Code Online (Sandbox Code Playgroud)


ano*_*knr 7

如果throws 单个发生多个,则可以使用运算符catch()识别哪个Exceptioninstanceof

java instanceof运算符用于测试对象是否指定类型(类,子类或接口)的实例

试试这个代码:-

        catch (Exception e) {
            if(e instanceof NotAnInt){

            // Your Logic.

            } else if  if(e instanceof ParseError){                

             //Your Logic.
            }
      }
Run Code Online (Sandbox Code Playgroud)

  • 该答案与已接受的(且有帮助的)答案不同,因为它专注于一种解决方案,该解决方案隐藏在示例中,并且在答案文本中未提及或解释。单独的 catch 块对我的问题不起作用,因为我正在研究单个异常类型的根本原因,所以我略读了这些答案。 (3认同)
  • 这与您写下答案 4 年前所接受的答案中所写的内容有何不同? (2认同)

Moh*_*mad 5

如果有人不知道该方法中抛出了什么类型的异常,例如具有多种可能性的方法,如下所示:

public void onError(Throwable e) {

}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式获取异常类

       Log.e("Class Name", e.getClass().getSimpleName());
Run Code Online (Sandbox Code Playgroud)

就我而言是UnknownHostException

然后按照instanseof前面的答案中提到的方法采取一些行动

public void onError(Throwable e) {
       Log.e("Class Name", e.getClass().getSimpleName());

       if (e instanceof UnknownHostException)
            Toast.makeText(context , "Couldn't reach the server", Toast.LENGTH_LONG).show();
       else 
          // do another thing
}
Run Code Online (Sandbox Code Playgroud)