I have a standalone app, I need to catch all exceptions. There's one case that when I disconnect the internet, I couldn't connect the database, and database operations are in another component. It'll give me the exception. I was thinking to use a global exception handling, it did catch the exception but I couldn't get the exact error message. Finally, the easiest way is to use try..catch block.
Here I do want to share the global exception handling I found online.
The first step is to define your own UncaughtExceptionHandler implementation
class.
import java.lang.Thread.UncaughtExceptionHandler;
public class CustomExceptionHandler implements UncaughtExceptionHandler
{
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("I caught an exception: " + e.getMessage());
}
}
The second step is to set the default uncaught exception handler.
public class Main
{
public static void main(String[] args) throws Exception
{
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
throw new Exception("I am exceptional!");
}
}
It works on my case, the only thing is that e.getMessage() always return null on my case.

本文分享了一种使用自定义全局异常处理程序的方法来捕获应用程序中未被捕获的异常。通过定义一个实现了UncaughtExceptionHandler接口的类,并将其设置为默认的异常处理器,可以有效地捕获并处理异常。然而,在实际应用中发现,某些情况下获取具体的错误消息存在局限性。

被折叠的 条评论
为什么被折叠?



