views:

57

answers:

3

Conditional Checking:

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

if FileExists('path/to/file'):
    // open file read & write.
else:
    // do something like informng 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'm frequently encountering situations like this. Which one to go for? Why?

+1  A: 

I think second snipet with exception handling is better because you can catch other exceptions generated by unpredicated errors.

And in many cases your instruction don't throw a exception when something going not good, then you must use condition to detect it, you can do it without exception catching or use it in try block with throw good instance of expeption class.

Svisstack
+5  A: 

As ever it depends.

In my opinion exceptions should be exceptional.

If you are routinely expecting that something might not work then you should do conditional checks. Conditional check code gets executed all the time regardless of whether there is a problem, so the checks shouldn't take a lot of time.

You should leave exception handling for rare or unlikely circumstances. So how likely is it going to be that the file won't exist?

I had a case where I wanted to write a file to a network drive, the code to check that the UNC share exists can take upto 30 seconds to timeout so you want to be using exceptions here!

AndyM
+1  A: 

In the first example, it's entirely possible that the file could be deleted between the check and the open, so you could get a FileNotExistsException anyway. In the Python community this is known as the LBYL (look before you leap) vs EAFP (easier to ask forgiveness than permission) debate, and Pythonic consensus is that EAFP is better in general.

Russell Borogove