[英]How can I get an error message as a string when I can't use the debugger
我希望能夠將整個錯誤日志保存到 java 中的字符串中。 例如,如果我有這條線
int a = 0/0
那么這會在調試器中給出以下錯誤消息:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at HelloWorld.main(HelloWorld.java:8)
我想要的是能夠將上述錯誤消息完全放在一個字符串中。 我已經嘗試在 try/catch 塊中包圍我想要錯誤字符串的代碼(對於這個例子,除以零),但這只會給我java.lang.ArithmeticException: / by zero
部分.
這是我的 try/catch 塊:
try{
int a = 0/0;
}catch(Exception e){
String a = getFullErrorString(e);
}
我的方法是:
public static String getFullErrorString(Throwable error){
return(
error.getCause() == null ? String.valueOf(error) : (error + "\n" + getFullErrorString(error.getCause()))
);
}
我需要這樣做,因為我的應用程序不能同時使用調試器和外部設備(外部設備使用 USB-C 端口,因此我無法在插入它的情況下進行調試,並且藍牙不是一個選項,因為我的應用大量使用藍牙)。 請幫忙!
這是一個 class 我發現對捕獲和記錄異常很有用:
String rootDir = Environment.getExternalStorageDirectory().getPath();
//----------------------------------------------------
// Define inner class to handle exceptions
class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e){
java.util.Date dt = new java.util.Date();
String fn = rootDir + "/YourFilenameHere_" + sdf.format(dt) + "_DBG.txt";
try{
PrintStream ps = new PrintStream( fn );
e.printStackTrace(ps);
ps.close();
System.out.println("wrote trace to " + fn);
e.printStackTrace(); // capture here also???
// SaveStdOutput.stop(); // close here vs calling flush() in class
}catch(Exception x){
x.printStackTrace();
}
lastUEH.uncaughtException(t, e); // call last one Gives: "Unfortunately ... stopped" message
return; //???? what to do here
}
}
Thread.UncaughtExceptionHandler lastUEH = null;
// Then in onCreate:
lastUEH = Thread.getDefaultUncaughtExceptionHandler(); // save previous one
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
堆棧跟蹤被寫入文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.