DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Know the JVM Series – 1 – The Uncaught Exception Handler

Know the JVM Series – 1 – The Uncaught Exception Handler

Yohan Liyanage user avatar by
Yohan Liyanage
·
Oct. 19, 10 · Interview
Like (0)
Save
Tweet
Share
15.05K Views

Join the DZone community and get the full member experience.

Join For Free

The Java API, backed by the JVM provides tons of features and facilities to Java developers, which could be used to get things done easily for certain specific scenarios. However, these features are often overlooked by developers, mainly due to the lack of reading material and  resources regarding these APIs. The purpose of this article series is to introduce such features of the JVM and Java API to intermediate Java developers.

Most of the content that will be discussed as part of this series may not be applicable for your day to day work, but knowing this will enable to you to utilize these to get things done simply, and elegantly.

As first part of the series, we will be looking at the Uncaught Exception Handler API of the JVM.  Java uses (or in more specific terms, throws) exceptions to notify exceptional situations in programs. Developers write try-catch blocks to handle these exceptions, or simply propagate the exceptions upwards in the call stack. The uncaught exception handler allows developers to provide a code segment to be executed when an exception is propagated up the call stack, without being caught.This is helpful when we need to perform some operations when exceptions occur, such as in safety critical applications.

In order to explain how the uncaught exception handling mechanism works, we need to have an understanding about the structure of Java Exceptions. The class hierarchy of Java  Exceptions are as follows.

Java Exceptions Class Hierarchy

An uncaught exception is a Throwable, which is not caught by any part of the application in the call stack where the exception occurred. It has propagated through the call stack, and has arrived at the underlying thread (could be the main thread or a defined thread), without being caught. The usual default behavior is to write the stack trace to System.err output stream. But we can override this default behavior by providing our own uncaught exception handler, by extending the Thread.UncaughtExceptionHandler interface.

The interface requires us to implement a single method, as follows.

public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
// Write the custom logic here
}
}

The first parameter, Thread t, is the thread in which the exception has occurred. The Throwable e, is the uncaught exception (or more specifically, the uncaught Throwable). You can provide any custom logic in this block, such as to write the error message to a specific log file, or to send an email indicating the error.

There are three places where this custom handler can be plugged in.

1. As the handler for a particular thread
When an uncaught exception occurs, the JVM initially looks for a handler registered for the particular thread. This can be set using Thread class method, public void setUncaughtExceptionHandler(handler) as in the following example.

public class MyRunnable implements Runnable {
public void run() {
// Other Code
Thread.currentThread().setUncaughtExceptionHandler(myHandler);
// Other Code
}
}

2. As the handler for a particular thread group
If the thread belongs to a thread group, then the JVM attempts to invoke the handler for the thread group, if no thread level handler was specified (as in Option 1).

ThreadGroup class implements the Thread.UncaughtExceptionHandler interface. So we need to subclass the ThreadGroup class to provide an alternative implementation.

The default implementation of java.lang.ThreadGroup class does the following, in the given order.

  • If a parent thread group is present, invoke its uncaughtException method.
  • If no parent thread group, but if a Default Handler is specified (using Option 3 below), invoke the default handler
  • If no default handler is given, write the stack trace to system error. But if the exception is ThreadDeath error, ignore it (this is a special circumstance).

3. As the default handler for the application (JVM)
The default thread handler will be invoked by the JVM if no handler is present by any of the above steps. To set the default handler, Thread class provides a static method, which can be used as follows.

Thread.setDefaultUncaughtExceptionHandler(myHandler);

If none of the above are available, then the JVM delegates to its default behavior, writing to system error as specified in the ThreadGroup class. This is because main thread also belongs to the 'main' ThreadGroup, which uses the default implementation.

The uncaught exception handlers are useful in scenarios where certain actions should be taken when a failure occurs in the application, such as notifying to a particular email address, or to log to a specific file. Instead of writing try-catch blocks to cover such scenarios, a better solution would be to implement an Uncaught Exception Handler.


View the original post, and similar posts at my blog.
Java (programming language) Java virtual machine

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Journey to Event Driven, Part 1: Why Event-First Programming Changes Everything
  • 5 Steps for Getting Started in Deep Learning
  • Important Takeaways for PostgreSQL Indexes
  • What “The Rings of Power” Taught Me About a Career in Tech

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: