Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can exception be perfectly replaced by if.. else?

I'm new to programming and I have a conceptual question.

That is, can "exception" be perfectly replaced by "if.. else" ?

I know "exception" is to handling some exceptional conditions that might cause error or crash.

But we also use "if.. else" to ensure the correctness of value of variables, don't we?

Or "exception" can really be replaced by "if.. else", but using "exception" has other benefits(like convenience?)

Thank you, and sorry for my poor English.

like image 515
尤川豪 Avatar asked Oct 27 '25 00:10

尤川豪


2 Answers

The biggest difference between exceptions and "if..else" is that exceptions pass up the call stack: an exception raised in one function can be caught in a caller any number of frames up the stack. Using "if" statements doesn't let you transfer control in this way, everything has to be handled in the same function that detected the condition.

like image 136
Ned Batchelder Avatar answered Oct 29 '25 21:10

Ned Batchelder


Most of your questions relate to Python, so here is an answer based on that fact.

In Python, it is idiomatic (or "pythonic") to use try-except blocks. We call this "EAFP": Easier to ask for forgiveness than permission.

In C, where there were no exceptions, it was usual to "LBYL": Look before you leap, resulting in lots of if (...) statements.

So, while you can LBYL, you should follow the idioms of the language in which you are programming: using exceptions for handling exceptional cases and if-statements for conditionals.

like image 41
Johnsyweb Avatar answered Oct 29 '25 19:10

Johnsyweb