查找异常类型

Dev*_*vin 1 java exception-handling exception

如果我有以下代码:

try {
    //some offensive code     
} catch (Exception e) {
    String type = //get type of e
    Assert.fail(type + " thrown.");
}
Run Code Online (Sandbox Code Playgroud)

有没有办法可以得到Exception的类型,所以我可以输出:

NullReferenceException thrown.
InvalidOperationException thrown.
OutOfMemoryException thrown.
Run Code Online (Sandbox Code Playgroud)

等等?我知道我可以使用instanceOf()打开不同的类型,但这假设我期待一个特定的类型.

FWIW,我知道这个特定的代码块非常糟糕,并且违反了Eric Lippert建议的许多最佳实践.我只是好奇是否有办法在运行时确定异常类型.

lop*_*san 6

你可以打电话e.getClass().getName()来获取课程名称.

getName()返回包括包的名称,例如java.lang.OutOfMemoryError.

getSimpleName()只返回一个类名,例如OutOfMemoryError.

请参阅类对象的 javadoc 以查看您可以获得的所有信息.