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. Java
  4. Unexceptional Uses of Java Exceptions

Unexceptional Uses of Java Exceptions

Want to learn more about exceptions in Java? Check out this post to learn more about handling exceptions in your project.

Eric Goebelbecker user avatar by
Eric Goebelbecker
CORE ·
Oct. 10, 18 · Tutorial
Like (14)
Save
Tweet
Share
10.43K Views

Join the DZone community and get the full member experience.

Join For Free

What's an Exception?

Oracle, the owners of Java, says:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Java (and many, if not most, other programming languages) provide an exception as a way to handle errors. When a severe error occurs, the program creates an object and "throws" it. It travels up the call stack until another object that is capable of handling the problem "catches" it. If no one catches it, the error can cause the thread, and even the whole program, to exit.

Depending on how your code uses them, adding a try/catch block to your code can be expensive, even if the exception is never thrown. If your code throws, the impact can be worse.

They also look a lot like a GOTO — enough said.

To me, exceptions are for exceptional events. We're running out of memory. An external resource is gone. A reference became a null.

When an Exception Is Not Exceptional

Here is the signature for a commonly used method in QuickFixJ, an API that I frequently use:

public String getString(int field) throws FieldNotFound


This is a method for retrieving the String value of a field in a FIX (Financial Information eXchange) message. If you ask for a value that is not there, it throws a FieldNotFound exception.

So, if you are working in an environment like mine, where whether or not a field exists is part of the message semantics, you end up doing this:

public String tagAsString(int tagId) {
  if (quickfixMessage.isSetField(tagId)) {
    return quickfixMessage.getString(tagId);
  }
    return "";
  }
}


I work on software that routes a few million messages a day. It determines where to send them by checking which fields are set and what their values are. To avoid the expense of the exceptions, I have to check the value twice.

For people that work with a strictly enforced dictionary, a missing tag might be an exceptional condition. They're like that TV lawyer that only asks questions she knows the answer to. Those of us that serve at the mercy of paying customers have to code around the developer's opinions about FIX messages.

To be fair to QFJ, I did a pull request and asked that the exception be replaced with an Optional, and the compromise was to add a  getOptionalString. This alleviated the problem where an Optional is useful and has that "expose your datatypes in your object names" vibe that I miss from old Win32 code. (Just like I miss buffer underflows while burning CDs.)

Spring JDBCTemplate and Empty Results

I recently started using Spring's JdbcTemplate and found myself writing this:

try {
  Map<String, Object> row = getJdbcTemplate().queryForMap(sql, sessionMemberId);
  return Optional.of(parseRow(sessionMemberId, row));
} catch (EmptyResultDataAccessException dae) {
  return Optional.empty();
}


Yes, an SQL query that results in an empty set is an Exception. To quote a StackOverflow answer, "Now, the correct way is not to catch this exception or theEmptyResultDataAccessException, but make sure the query you are using should return only one row."

So, rather than use your database to store data and then query it for relationships, you should know the relationships in advance. And if you don't, let the app crash with an uncaught exception.

Does a query returning an empty set "disrupt the normal flow of the program?"

In the case of the SQL query, just no. Never. Absolutely not. Why does  EmptyResultDataAccessException exist? In what world does an empty result "disrupt the normal flow of the program?"

Let's look at another snippet of code in the same program, using the same Spring object:

List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
if (rows.isEmpty()) {
  return new ArrayList<>();
}


In this case,  I'm querying for a list. If the result set is empty, the return is an empty list.

So, I'd have to say that an empty result doesn't disrupt the normal flow of the program.  EmptyResultDataAccessException is enforcing an opinion, not communicating an error.

Java is a verbose and often noisy language. Let's try to not make it worse with unneeded try/catch blocks.

Java (programming language)

Published at DZone with permission of Eric Goebelbecker, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed Stateful Edge Platforms
  • How to Cut the Release Inspection Time From 4 Days to 4 Hours
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • A Simple Union Between .NET Core and Python

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: