1

I have read this and this and this: if my question misses the point in those answers, please point it out and we'll get this one deleted. These questions indicate that this may actually be a bad thing under certain circumstances, but I think I understand that difference.

QUESTION: If I am using a function from another library that throws an unchecked exception that can be corrected, AND I want to be safe, AND my program will be outputting directly to the user (there should be no reason to fail completely), do I:

  1. handle these individually AND include a catch-all catch block with a general unchecked Exception (say to request user input again)?
  2. handle the specific exceptions individually AND declare throws exception passing it to the caller?
  3. handle the specific exceptions AND leave the general exception out altogether?

What is standard / defensive / unecessary programming?

user58446
  • 327

1 Answers1

1

If I am using a function from another library that throws an unchecked exception that can be corrected

If you got an exception you specifically can do something about at the current code level, by all means catch it specifically and do your thing.

AND my program will be outputting directly to the user (there should be no reason to fail completely)

The question should rather be whether the code you're looking at directly outputs to "the user".

If you're at an interface boundary(*) (e.g. GUI action vs. function call) that you only have two choices:

  • Catch Exception and inform the "user" in a general way that whatever he did failed. (With as much or as little info as you deem necessary.)
  • Do not catch Exception and either die or have your specific interface boundary handle - or not - it in a (very?) generic way (which may include just aborting the program).

So as I see this, #2 is often undesirable, so the question then becomes where to catch(Exception). I'd say do it at an interface boundary, and possibly only there. As high up as possible, but not higher - probably not at the catch block where you handle the specific 3rd part exceptions, unless the full operation is basically just the call to the 3rd party code.

In my book, defensive here would mean to make sure your handling code works in a deterministic way in the face of an unknown Exception, it does not mean you have to add the unknown to the handler block where you handle the specific. Basically it amounts to writing "exception safe code" so that your code always works in the face of exceptional exceptions.


(*) "interface boundary" - loose term here. Do not get caught up on it.

Martin Ba
  • 7,862