Junior — Middle
What methods can be used to handle uncaught exceptions in a program?
sobes.tech AI
Answer from AI
In Java, to handle unchecked exceptions, several approaches can be used:
- Global exception handler via
Thread.setDefaultUncaughtExceptionHandlerAllows setting a handler that will be invoked when an unchecked exception occurs in any thread.
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
System.err.println("Uncaught exception in thread " + thread.getName() + ": " + throwable);
// Logging, resource cleanup, etc.
});
-
Handling exceptions in the main method Wrap the main code in try-catch blocks to catch unhandled exceptions.
-
Using AOP (Aspect-Oriented Programming) In Spring and other frameworks, aspects can be configured to intercept exceptions at method level.
-
Handling exceptions in UI frameworks For example, in Swing, you can override
Thread.setDefaultUncaughtExceptionHandlerfor exceptions in the Event Dispatch Thread (EDT).
These methods allow centralized handling of uncaught exceptions, helping to prevent abrupt program termination and improve error diagnostics.