How To Write Safe Code: Checking Vs State Exception Handling?

Conditional check:

if denominator == 0:
    // do something like informing the user, or skipping this iteration.
else:
    result = numerator/denominator

if FileExists('path/to/file'):
    // open file read & write.
else:
    // do something like informing the user, or skipping this iteration.

Exception Handling:

try:
    result = numerator/denominator
catch (DevidedByZeroException):
    //take action

try:
    //open file read & write.
catch (FileNotExistsException):
    //take action

I often encounter such situations. Who to go to? Why?

+3
source share
3 answers

As always, it depends.

In my opinion, exceptions should be exceptional.

If you regularly expect that something might not work, you should perform conditional checks. The conditional verification code runs all the time, regardless of whether there is a problem, so the verification should not take much time.

You must leave exception handling for rare or unlikely circumstances. So how likely is the file to not exist?

, , , UNC 30 , !

+5

, , , .

, - , , try block expeption.

+1

, , FileNotExistsException. Python LBYL ( , ) EAFP ( , ), Python , EAFP .

+1

Source: https://habr.com/ru/post/1754387/


All Articles