Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

10
  • 1
    What if the exception is of kind that can't be delegated and should be dealt with internally? Commented Jun 11, 2014 at 9:52
  • 2
    @LimboExile: I think that you could still deal with it internally and then, maybe throw another exception, maybe your own. This would illustrate that something that shouldn't have happened took place, but at the same time, you did not expose what is really going under the hood, which I assume is why you want to deal with the exception internally. Commented Jun 11, 2014 at 9:57
  • 6
    It's perhaps worth bearing in mind that throwing an exception should be for an exceptional case. If it is common or normal for DoStuff to fail, throwing an exception for the failure case would be akin to controlling program flow with exceptions which is bad. Exceptions also have an inherent performance cost. If DoStuff failing is an uncommon case due to an error, then exceptions definitely are the way to go as @npinti suggests. Commented Jun 11, 2014 at 14:54
  • 1
    @KarlNicoll Whether something is "exceptional" is completely subjective. The main criteria should be whether you want the program to crash if no one does something about the error, and whether you want the possibility of error to be present in the function's type. Additionally, it's not a fact that exceptions are expensive; it depends on the language and how you throw them. Exceptions are cheap in Python, and if you strip the stack trace information they can be cheap in Java as well. Even if there was a performance cost, it's premature optimization to worry about it until you've profiled. Commented Jun 11, 2014 at 15:05
  • 1
    @Doval - I agree that it's subjective, which is why OP shouldn't discount npinti's answer entirely, as it could well be the best course of action. My point was that throwing exceptions isn't always the best path to take. There are plenty of cases where a failure doesn't justify throwing an exception and potentially crashing an application. For example, if OP's DoStuff() method cleans up after the inner code throws an exception, and the Post-conditions of the method are still correct, a return code may be a better option as the error has been handled. Commented Jun 11, 2014 at 15:52