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. Data Engineering
  3. IoT
  4. Robust Exception Handling

Robust Exception Handling

Handle exceptions like a champ.

Radek Hecl user avatar by
Radek Hecl
·
Feb. 08, 19 · Tutorial
Like (12)
Save
Tweet
Share
27.42K Views

Join the DZone community and get the full member experience.

Join For Free

Oh no, don't do this to me...

// Writing comment that exception is skipped
try {
    throw new IOException("Made up");
} catch (IOException e) {
    // skip it
}

// Logging and moving on
try {
    throw new IOException("Made up");
} catch (IOException e) {
    log.error("blah blah blah", e);
}

// Creating TODO instead of actually doing the job
try {
    throw new IOException("Made up");
} catch (IOException e) {
    // TODO - handler it (;
}


.... and still, I am finding those catch blocks inside various projects. This is a great way to suppress the problem — for a short period of time. A few weeks or months later, this will become a nightmare for developers. Walking through the old log files and trying to figure out what went wrong is definitely not that most people want to do. Therefore, let's avoid that.

The first rule is that catch blocks are here to handle exceptional situations. Logging exceptions and moving on is not considered as handling. The only case when it makes sense to suppress exception is during the closing of the resource after a prior exception (this case isn't covered within this article; if you are interested, then here is an old yet still very good blog post written by McDowell).

There are three basic patterns of how to handle exceptions: translate, retry, and recover.

Translate is often used when you have to deal with a checked exception, your method can't bubble it up, and recovery is not possible. In such cases, it is appropriate to translate it into a runtime exception and throw up. Then, the runtime exception is typically handled in the framework level. Retry is useful when dealing with unreliable services. It makes sense only if retrying makes sense fundamentally. The good example is retrying to overcome network interruptions. Recover is good when the strategy for doing that is defined. For example, you can write data to the local storage if sending over network fails. Of course, then it's necessary to define what to do with that file.

In addition, the mentioned patterns might be combined. Examples are as follows.

// Translate
try {
    throw new IOException("Made up");
} catch (IOException e) {
    throw new RuntimeException(e);
}

// Retry - give up after 5 tries
boolean end = false;
int count = 0;
while (end == false) {
    try {
        // Send message.
        if (true) {
            throw new MessagingException("Made up");
        }
        end = true;
    } catch (MessagingException e) {
        if (count >= 5) {
            // Give up after 5 tries.
            throw new RuntimeException("was not able to send message even after five tries", e);
        }
        ++count;
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e1);
        }
    }
}

// Recover - write to file if a transfer fails
try {
    // Send message.
    throw new MessagingException("Made up");
} catch (MessagingException e) {
    try {
        // Write to file.
        throw new IOException("Made up");
    } catch (IOException e1) {
        // No more recovery if writing to file fails.
        throw new RuntimeException(e1);
    }
}


If everything fails, then this way will at least guarantee that you will be aware of the problem. In addition, it will provide you always the true cause of the issue; therefore, you will be able to quickly identify where the problem is!

Happy handling!

Blocks Network Framework Data (computing) dev POST (HTTP) IT Blog

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Getting a Private SSL Certificate Free of Cost
  • Asynchronous Messaging Service
  • How To Best Use Java Records as DTOs in Spring Boot 3
  • NoSQL vs SQL: What, Where, and How

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: