How can I get the line number where the exception was thrown using Thread.UncaughtExceptionHandler?

前端 未结 2 925
太阳男子
太阳男子 2020-12-14 06:49

When I use a try-catch block to catch an exception, I can get the line number where the exception was thrown by calling e.getStackTrace().

Like this:

2条回答
  •  抹茶落季
    2020-12-14 07:07

    Inspired by Thilo and 范植勝 here the copy 'n paste version for the lazy people:

    public class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
        final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            Log.ee(thread.getClass().getName(),
                    throwable.getMessage(),
                    "Error in " + Arrays.toString(throwable.getCause().getStackTrace()));
            if (uncaughtExceptionHandler != null) {
                // let Android know what happened
                uncaughtExceptionHandler.uncaughtException(thread, throwable);
            } else {
                // kill process
                System.exit(-1);
            }
        }
    }
    

    Note: Log.ee is a custom file writer

    public static void ee(String tag, String msg, String msg2) {
        try {
            String ts = Utils.getReadableTimeStamp();
            File dir = new File(Environment.getExternalStorageDirectory() + "/" + Const.CRASH_DIR);
            dir.mkdirs();
            PrintWriter printWriter = new PrintWriter(new FileWriter(new File(dir, "errors-" + sImei + ".log"), true));
            printWriter.print("-------------------------------\r\n");
            printWriter.print(ts + ":\r\n");
            printWriter.print(tag + "\r\n");
            printWriter.print(msg + "\r\n");
            printWriter.print(msg2 + "\r\n");
            printWriter.print("-------------------------------\r\n");
            printWriter.flush();
        } catch (IOException e) {
            android.util.Log.e(Log.class.getName(), "ee -> IOException", e);
        }
    }
    

提交回复
热议问题