Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what can't be done with if else clause, and can be done with exception handling?

what can't be done with if else clause, and can be done with exception handling ?

In other words where do we actually need to use exception handling and mere if else won't serve the purpose.

Is exception handling just a glorified way of showing errors ?

like image 933
Ess Avatar asked Jan 20 '23 13:01

Ess


1 Answers

In the earliest C++ implementations, exceptions were compiled into equivalent if/else constructs, more or less. And they were slow as molasses, to the point where you can still find programming guides that recommend against exceptions on the grounds that "they are slow".

So it is not a question of "can" or "cannot". It is a question of readability and performance.

Littering every line of your code with error checks makes it harder for a human to follow the non-exceptional (i.e. common) case. And as every good programmer knows, the primary audience for your code is human readers.

As for performance, if/else is slower than a modern exception implementation. Modern implementations incur literally zero overhead except when an exception is actually thrown. If your exceptions truly represent "exceptional" cases, this can be a significant performance difference.

like image 147
Nemo Avatar answered Apr 06 '23 20:04

Nemo