Uncatchable ChuckNorrisException

前端 未结 17 2145
时光取名叫无心
时光取名叫无心 2020-12-02 03:34

Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?

Thoughts that came to m

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 03:57

    It is easily possible to simulate a uncaught exception on the current thread. This will trigger the regular behavior of an uncaught exception, and thus gets the job done semantically. It will, however, not necessarily stop the current thread's execution, as no exception is actually thrown.

    Throwable exception = /* ... */;
    Thread currentThread = Thread.currentThread();
    Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
        currentThread.getUncaughtExceptionHandler();
    uncaughtExceptionHandler.uncaughtException(currentThread, exception);
    // May be reachable, depending on the uncaught exception handler.
    

    This is actually useful in (very rare) situations, for example when proper Error handling is required, but the method is invoked from a framework catching (and discarding) any Throwable.

提交回复
热议问题