Is it wrong to add fields to exceptions? I have a problem that happens and I'm thinking of adding considerable information to an exception, but it sounds weird: an exception with getters.

What you think about this?


What's wrong with it? Exceptions are still objects, they are just passed in a different way when being thrown.


Properties can make exceptions be more informative than just an exception message that (supposedly) is human-readable. If you catch the exception, you can receive information regarding the issue, and probably fix it automatically.


The java.sql.SQLException class has the String SQLState and vendorCode properties, also with simple getters.

  • I think the problem it's using exception like a flow control instead of a really exception. – user3452444 Jul 1 '16 at 20:00
  • @user3452444 this depends on how you are using it. After all, if your program stack has to break several levels up to pass the exception to the catch block, terminating the execution of several methods, there aren't many cases that such operation isn't an "exception"/error. From another thought, if your method stops executing in the middle, it already matches the definition of an exception! (Of course, unless you abuse exception throws as a de facto hybrid/union method return type) – SOFe Jul 6 '16 at 15:04

I like to quote Bill Venners saying, "Throw exceptions at programmers, not at code." I think it's a good rule of thumb.

Why not concatenate all information into the description string of the exception? The cost of String concatenation won't be incurred unless the exception is thrown. You aren't going to do anything with that info besides print it out anyway. Are you?

Unless, you actually want your program to react to the exception in some way. In which case, I'd again turn to Bill Venners "Or" class. He presented it in his Functional Error Handling talk. It holds an object (just like Optional or Maybe) which can either be a Good<T> value or a Bad<U> value. A Java Or is available as well.

Just because you can do more with exceptions doesn't mean that you should. Functional programmers eschew them altogether because they are a side effect, and an escape hatch from your code that is hard to reason about.

  • I have a method to find the intersection points of two equations. If there is a continuous range of intersection, I throw a throwable (class ContiuousIntersectionThrowable extends Throwablebut not an exception to separate it from the general case of exceptions). Is this an abuse? – SOFe Jul 8 '16 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.