我正在编写一个游戏程序,很少会遇到异常。我希望能够在单独的线程上记录我遇到的所有异常。我的程序已经是多线程的了。在某些情况下,我使用 try catch,对于那些我可以将异常变量设置为捕获的异常。不过,我希望能够找出所有线程上引发的所有异常,而无需将每个语句都放入 try catch 中。为了澄清起见,我想要异常对象而不仅仅是异常的名称。
最佳答案
您想要 Thread.UncaughtExceptionHandler :
Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.
参见here了解详情。
关于java - 跟踪程序中的所有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899559/