gpt4 book ai didi

Java异常处理获取控制台错误信息

转载 作者:行者123 更新时间:2023-12-01 12:25:54 24 4
gpt4 key购买 nike

我想在生成异常时使用java获取错误消息。

现在我有以下场景的java代码:

method first(){

try{
second();
}catch(Exception e){
System.out.println("Error:> "+e)
}

}
<小时/>
method second(){

try{
my code
}catch(Exception e){
throw new Exception("Exception generate in second method",e);
}

}

现在,当第一个方法执行时,我只收到“第二个方法中生成异常”消息,但 java 在控制台上打印了一些其他消息,那么如何获取该控制台错误消息。

注意:我已经尝试过 e.getMessage();和 e.printStackTrace();

最佳答案

每个异常都有一个可以通过 getCause() 获取的原因。您可以递归地向下查找,直到找到根本原因。下面是一个实用程序的示例,该实用程序可以像控制台一样转储异常及其所有原因。

private void first() {
try {
second();
} catch (Exception ex) {
Log.e("CATCH", getExceptionDump(ex));
}
}

private void second() {
try {
throw new UnsupportedOperationException("We don't do this.");
} catch (Exception ex) {
throw new RuntimeException("Exception in second()", ex);
}
}

private String getExceptionDump(Exception ex) {
StringBuilder result = new StringBuilder();
for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
if (result.length() > 0)
result.append("Caused by: ");
result.append(cause.getClass().getName());
result.append(": ");
result.append(cause.getMessage());
result.append("\n");
for (StackTraceElement element: cause.getStackTrace()) {
result.append("\tat ");
result.append(element.getMethodName());
result.append("(");
result.append(element.getFileName());
result.append(":");
result.append(element.getLineNumber());
result.append(")\n");
}
}
return result.toString();
}

关于Java异常处理获取控制台错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26336437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com