Conditional Checking:
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’m frequently encountering situations like this. Which one to go for? Why?
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!