Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw an exception from a lambda expression, bad habit?

Tags:

c++

c++11

I´m currently parsing a queue of tokens: Instead of checking if the queue is empty for each subsequent pop() i´ve written a lambda throwing an exception if queue.begin() == queue.end(). I wonder if this a good, "proper" implementation or if it´s generally considered to be a bad practice to throw an exception from a lambda expression?

like image 291
quiZ___ Avatar asked Sep 02 '25 16:09

quiZ___


2 Answers

Throwing an exception from a lambda function is equivalent like throwing an exception from any other function.

Now if it's a good practice in such a context to throw an exception, in my humble opinion is not. Exceptions are meant to be used in exceptional situations (e.g., a bullet pierced your CPU) and I don't think that reaching the end of a range qualifies as such (i.e., exceptional).

like image 107
101010 Avatar answered Sep 08 '25 03:09

101010


I think its depends on what you are trying to accomplish. I personally would leave the check for an empty queue to the function where the pop is called in. There seems to be no reason to limiting the capabilities of your queue with the exception. There might be some cases you want to handle when the queue is empty, but throwing an exception and handeling this seems to lead to bloating the code to me.

Just my preference.

like image 28
user1109410 Avatar answered Sep 08 '25 02:09

user1109410