How to handle failed methods:
The first approach is when something goes wrong to throw an exception. But the problematic code needs to be placed in a try block, and then you need to write the catch block.
The second approach you need to check the return value from the method, and then do something.
So basically isn't it the same mechanism? You have two parts: detecting that something goes wrong and then doing something about it. So does it matter then which approach I use?
The main benefit with exceptions is that they are non-local. You can catch an exception several invocation layers away from where it was thrown. That way, code in between doesn't have to care about exceptions (except ensuring proper cleanup during unwinding, i.e. being exception safe), which makes it less likely that an exceptional situation gets forgotten. But this benefit comes at a price: stack unwinding is more complicated than simply returning a value. In terms of performance, the return value approach is usually simpler.
So I'd use these to choose: if for some reason the only reasonable place to deal with a problem is directly at the location where the function was called, and if you are fairly certain that every caller will include some kind of error handling code in any case, and is not likely to forget doing so, then a return value would be best. Otherwise, I'd go for an exception.
Basically you can reach the same behavior with both approaches, but Exception can give 2 added values:
1) You don't have to handle the error in the exact calling method, it can be anywhere up the call stack. this remove the if(!doSomthing()) return false;
from the code when you just want to pass the error up.
2) It allow you to write a block of code, under one try
and handle all the errors under it in one catch
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With