1

Is the following static helper function an anti-pattern?

public class CustomException extends RuntimeException {
    // ...
    public static void rethrow(String s, Exception e) throws CustomException {
        throw new CustomException(s + "\n" + "Exception: " + e.getMessage());
    }
}

Couldn't see it on http://javapeanuts.blogspot.com/2012/02/exception-management-antipatterns.html or elsewhere.

One immediate problem is that static warnings get broken, eg I can't do the following anymore:

final Blah blah = null;
try {
    blah = foo();
}
catch (Exception e) {
    CustomException.rethrow("Couldn't blah", e);
}
bar = blah.bar(); // ERROR: Variable 'blah' might not have been initialized.

Hmmmm, I think I solved it. :-) I should create a constructor for CustomException that takes a String and Exception as args.

teobais
  • 2,820
  • 1
  • 24
  • 36
jones77
  • 505
  • 1
  • 4
  • 16

1 Answers1

2

Yes, catching the RuntimeException and creating a new path inside your application isn't allowed, because it's completely wrong to catch the RuntimeException, as the main reason that it has been thrown has to mainly do with things like the resources of your system for example and such other things, not related with your code.

Instead, you should terminate the specified code's flow and inform the user respectively.

But, there are some cases that the depicted anti-pattern may sound better, so, you would better go through the following threads, in order to develop a better idea, according to your problem, at any given time:

The above are not more than words, which means that in the end, the final design (i.e. following the language specification/creating anti-patterns) is up to you, but what you should always keep in mind (and decide/act accordingly, per case) is that one layer's runtime exception is another layer's checked (and acted upon) exception.

Community
  • 1
  • 1
teobais
  • 2,820
  • 1
  • 24
  • 36
  • Cool, thanks for your links and thoughts. What I needed in the first instance is a constructor, not a helper function, ie: `public CustomExceptionString s, Exception e) { super(s + "\n" + "Exception: " + e.getMessage()); }` – jones77 Jan 20 '16 at 18:39