Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle failed methods: by using exceptions or making the methods return bool?

Tags:

c++

c++11

How to handle failed methods:

  1. using exceptions
  2. making the methods return bool

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?

like image 665
user3111311 Avatar asked Dec 19 '13 13:12

user3111311


2 Answers

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.

like image 115
MvG Avatar answered Sep 22 '22 16:09

MvG


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.

like image 38
Roee Gavirel Avatar answered Sep 23 '22 16:09

Roee Gavirel