
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Handle Exception Using UncaughtExceptionHandler in Java
The UncaughtExceptionHandler is an interface inside a Thread class. When the main thread is about to terminate due to an uncaught exception the java virtual machine will invoke the thread’s UncaughtExceptionHandler for a chance to perform some error handling like logging the exception to a file or uploading the log to the server before it gets killed. We can set a Default Exception Handler which will be called for the all unhandled exceptions. It is introduced in Java 5 Version.
This Handler can be set by using the below static method of java.lang.Thread class.
public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler ueh)
We have to provide an implementation of the interface Thread.UncaughtExceptionHandler, which has only one method.
Syntax
@FunctionalInterface public interface UncaughtExceptionHandler { void uncaughtException(Thread t, Throwable e); }
Example
public class UncaughtExceptionHandlerTest { public static void main(String[] args) throws Exception { Thread.setDefaultUncaughtExceptionHandler(new MyHandler()); throw new Exception("Test Exception"); } private static final class MyHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("The Exception Caught: " + e); } } }
Output
The Exception Caught: java.lang.Exception: Test Exception
Advertisements