Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's Your ShouldNeverHappenException? [closed]

Tags:

java

exception

Java's checked exceptions sometimes force you to catch a checked exception that you believe will never be thrown. Best practice dictates that you wrap that in an unchecked exception and rethrow it, just in case. What exception class do you wrap with in that case?

What exception would you wrap with in the "// Should never happen" case?

like image 294
Dhanapal Avatar asked Jul 14 '09 12:07

Dhanapal


Video Answer


1 Answers

I don't yet have one, but I'd do it the following way:

  • have it extend Error rather then Exception/RuntimeException, since then it's less likely to be caught by an error handler which is not prepared for it;
  • wrap it in some static utility calls:

Example:

public static void doAssert(boolean result, String reason) {

    if ( !result ) 
        throw new OMGWereDoomedError("Assertion failed: " + reason + " .");
}

I prefer these wrapper since I can then change the implementation if needed.

Also, I don't advocate using assertions since I don't always control the runtime flags, but I do want execution to halt abruptly if the system is compromised.

Consider this:

  • showing the user a Sorry, we're unable to process your payment page;
  • confirming the result to the user, even though the system is in an uncertain state.

Which would you choose?

like image 162
Robert Munteanu Avatar answered Oct 13 '22 00:10

Robert Munteanu