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
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
  1. DZone
  2. Coding
  3. Languages
  4. Catch Me If You ... Can't Do Otherwise

Catch Me If You ... Can't Do Otherwise

Maybe you also see this mistake everywhere in Java programmers' code—exceptions being caught but not re-thrown? Here's some advice on handling excptions...

Yegor Bugayenko user avatar by
Yegor Bugayenko
·
Jul. 10, 15 · Tutorial
Like (1)
Save
Tweet
Share
13.67K Views

Join the DZone community and get the full member experience.

Join For Free

i don't know whether it's an anti-pattern or just a common and very popular mistake, but i see it everywhere and simply must write about it. i'm talking about exception catching without re-throwing . i'm talking about something like this java code:

try {
  stream.write(data);
} catch (ioexception ex) {
  ex.printstacktrace();
}


image title

©catch me if you can (2002) by steven spielberg

pay attention: i don't have anything against this code:

try {
  stream.write('x');
} catch (ioexception ex) {
  throw new illegalstateexception(ex);
}

this is called exception chaining and is a perfectly valid construct.

so what is wrong with catching an exception and logging it? let's try to look at the bigger picture first. we're talking about object-oriented programming — this means we're dealing with objects. here is how an object (its class, to be exact) would look:

final class wire {
  private final outputstream stream;
  wire(final outputstream stm) {
    this.stream = stm;
  }
  public void send(final int data) {
    try {
      this.stream.write(x);
    } catch (ioexception ex) {
      ex.printstacktrace();
    }
  }
}


here is how i'm using this class:

new wire(stream).send(1);


looks nice, right? i don't need to worry about that ioexception when i'm calling send(1) . it will be handled internally, and if it occurs, the stacktrace will be logged. but this is a totally wrong way of thinking, and it's inherited from languages without exceptions, like c.

exceptions were invented to simplify our design by moving the entire error handling code away from the main logic. moreover, we're not just moving it away but also concentrating it in one place — in the main() method, the entry point of the entire app.

the primary purpose of an exception is to collect as much information as possible about the error and float it up to the highest level, where the user is capable of doing something about it. exception chaining helps even further by allowing us to extend that information on its way up. we are basically putting our bubble (the exception) into a bigger bubble every time we catch it and re-throw. when it hits the surface, there are many bubbles, each remaining inside another like a russian doll. the original exception is the smallest bubble.

when you catch an exception without re-throwing it, you basically pop the bubble. everything inside it, including the original exception and all other bubbles with the information inside them, are in your hands. you don't let me see them. you use them somehow, but i don't know how. you're doing something behind the scenes, hiding potentially important information.

if you're hiding that from me, i can't promise my user that i will be honest with him and openly report a problem when it occurs. i simply can't trust your send() method anymore, and my user will not trust me.

by catching exceptions without re-throwing them, you're basically breaking the chain of trust between objects.

my suggestion is to catch exceptions as seldomly as possible, and every time you catch them, re-throw.

unfortunately, the design of java goes against this principle in many places. for example, java has checked and un-checked exceptions, while there should only be checked ones in my opinion (the ones you must catch or declare as throwable). also, java allows multiple exception types to be declared as throwable in a single method — yet another mistake; stick to declaring just one type. also, there is a generic exception class at the top of the hierarchy, which is also wrong in my opinion. besides that, some built-in classes don't allow any checked exceptions to be thrown, like runnable.run() . there are many other problems with exceptions in java.

but try to keep this principle in mind and your code will be cleaner: catch only if you have no other choice.

p.s. here is how the class should look:

final class wire {
  private final outputstream stream;
  wire(final outputstream stm) {
    this.stream = stm;
  }
  public void send(final int data)
    throws ioexception {
    this.stream.write(x);
  }
}


Java (programming language) Object-oriented programming Anti-pattern Trust (business) Object (computer science) IT Design app

Published at DZone with permission of Yegor Bugayenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 12 Biggest Android App Development Trends in 2023
  • How Do the Docker Client and Docker Servers Work?
  • Using JSON Web Encryption (JWE)
  • Remote Debugging Dangers and Pitfalls

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: