Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle a typical precondition exception?

Tags:

exception

Which of the following ways of handling this precondition is more desirable and what are the greater implications?

1:

If Not Exists(File) Then 
    ThrowException
    Exit
End If
File.Open
...work on file...

2:

If Exists(File) Then 
    File.Open 
    ....work on file...
Else
    ThrowException
    Exit
End 

Note: The File existence check is just an example of a precondition to HANDLE. Clearly, there is a good case for letting File existence checks throw their own exceptions upwards.

like image 861
Matias Nino Avatar asked Nov 21 '25 08:11

Matias Nino


2 Answers

I prefer the first variant so it better documents that there are preconditions

like image 177
dfa Avatar answered Nov 25 '25 00:11

dfa


Separating the pre-condition check from work is only valid if nothing can change between the two. In this case an external event could delete the file before you open it. Hence the check for file existence has little value, the open call has to check this anyway, let it produce the exception.

like image 26
djna Avatar answered Nov 24 '25 22:11

djna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!