[英]Get exception instance class name
我想知道在這種情況下異常實例是什么:
try {
// some risky actions
} catch (Exception e) {
System.out.println("Get instance name there");
}
我怎樣才能做到這一點?
干得好:
try {
throw new ArithmeticException();
} catch (Exception e) {
System.out.println( e.getClass().getCanonicalName());
}
輸出:
java.lang.ArithmeticException
異常類型顯示為以下輸出的一部分:
e.printStackTrace();
要以編程方式獲取它,您可以使用:
String exceptionClassName = e.getClass().getName();
根據 catch 塊中的異常子類型具有邏輯是一種糟糕的形式。 Sonar 會將此標記為違反代碼 ( squid S1193 )。
相反,您應該添加多個 catch 塊來捕獲不同類型的異常:
try {
readFile(fileName);
}
catch (java.io.IOException e) {
LOG.error("Error accessing file {}", fileName, e);
}
catch (java.lang.IllegalArgumentException e) {
LOG.error("Invalid file name {}", fileName, e);
}
注意:從Log4j 2(和 SLF4J 1.6+)開始,您可以添加一個 throwable 作為最后一個參數,它將被識別為這樣。 所以上面會起作用!
從 Java 7 開始,您還可以執行multi-catch :
}
catch (java.io.IOException | java.lang.IllegalArgumentException e) {
LOG.error("Could not read the file {}", fileName, e);
}
多捕獲的好處是您可以在單個捕獲塊中處理多種異常類型,而不必恢復到包含您不想處理的異常類型的公共超類(如java.lang.Exception
)。
默認異常日志記錄類似於
try
{
//
}
catch (Exception e)
{
e.printStackTrace();
}
這會將異常的堆棧跟蹤打印到 system.err
如果您想添加一些上下文信息,可以查看Apache Commons ContextedRuntimeException
public static void main(String[] args) {
try {
doSomething();
} catch (ContextedRuntimeException e) {
System.out.println(e.getMessage());
System.out.println(e.getContextEntries());
}
}
private static void doSomething() {
int divisor = 0;
int dividend = 100;
int result;
try {
result = dividend / divisor; // Just throw an exception to test things....
System.out.print("DIVISION RESULT: "+result);
} catch (ArithmeticException e) {
throw new ContextedRuntimeException("Oops..division by zero not allowed", e)
.addContextValue("Divisor", divisor)
.addContextValue("Dividend", dividend);
}
}
會輸出:
Oops..division by zero not allowed
Exception Context:
[1:Divisor=0]
[2:Dividend=100]
---------------------------------
[(Divisor,0), (Dividend,100)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.