0

Is there any reason why it's better to use a try/catch statement when one can check to see if a value that is designated to indicate a problem is returned?

For example a function prime factors a number. If a negative integer is passed to it would it be "better" for an exception to be thrown or a particular value returned (that would never be a legitimate value, say -1).

If a function doesn't need to return something would it be less efficient to return true on success and false on failure, as opposed to throwing something?

4

2 回答 2

1

Exceptions can propagate up across multiple call frames at a time without any extra code in the intervening call frames to check for error conditions/returns. This means they have the potential to yield better performance (at least in the non-error case) than code that's based on return value checks at every call level. That's probably the main concrete benefit.

于 2012-08-16T05:15:41.267 回答
0

The use of a Try/Catch versus returning a boolean value has been discussed for a while. I found this StackOverflow article that might add some insight. For myself I tend to use both the Try/Catch and the boolean return. It depends when a method is being called. As well, sometimes it is best to let an error bubble up the stack so it can be caught and dealth with effieciently.

Finally, if your find you are not getting any answers here you can also try https://softwareengineering.stackexchange.com/

于 2012-08-14T20:23:45.783 回答