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

前端 未结 2 924
太阳男子
太阳男子 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);
        }
    }
    
    0 讨论(0)
  • 2020-12-14 07:11

    Try

    e.getStackTrace()[0].getLineNumber();
    

    The first element in the stack trace is the most recently called method (the top of the call stack).

    There are also methods to get the class, method and file name.

    If the e you get in the UncaughtExceptionHandler does not work well for you (because it wraps the real exception), you can try e.getCause() and look at that stack trace.

    0 讨论(0)
提交回复
热议问题