Search code examples
programming-languages

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.


Solution

  • 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.