Peter
Peter

Reputation: 393

Catch exception, re-throw assertion

Consider following example. Is it considered a bad practise?

Note: I know re-throwing exception is ok, but what about assertionerror?

public static main(){
    try {
        doSmth();
    } catch (WhateverException we) {
        throw new AssertionError(e.getMessage());
    }
}

public static void doSmth() throws WhateverException { }

Upvotes: 0

Views: 250

Answers (1)

Sneftel
Sneftel

Reputation: 41474

It's not bad practice to throw an error in response to an exception, if the exception indicates a situation that is fatal for your code. However:

  • There's no need to use AssertionError in particular. I mean, it's fine if you do, since nobody's going to be catching one, but you should consider just doing Error instead, so that somebody doesn't go looking for the assert statement that they assumed caused it.
  • When chaining a throwable like that, always use the old exception to construct the new one: throw new AssertionError(we). That'll keep the old stack trace around. You can (and should) also pass a custom message.

Upvotes: 2

Related Questions