I got the question:
“What do you prefer, exception handling or if-condition?”
for an interview. My answer was that exception handlers are preferred only for exceptional circumstances like a disk permission error on file write. The interviewer seemed to be expecting some other answer. What is the correct answer?
EDIT: Any particular example where exception handling is commonly used when an if-condition would have been more appropriate?
As this question is tagged “C#”, we can refer to the .NET Framework Design Guidelines as a good starting point for answering these types of questions. This is the guidance given on MSDN under “Exception Throwing”:
Here is an example of a bad practice where an exception is handled but can nearly always be avoided:
This seems contrived but I see code like this quite often from newer programmers. Assuming proper synchronization around reads and writes to
array, this exception can be 100% deterministically avoided. Given that, a better way to write that code would be the following:There are other cases where you cannot reasonably avoid exceptions and just need to handle them. This is most commonly encountered when you have to deal with external resources such as files or network connections which you could potentially lose access to or contact with at any time. Example from WCF:
Even in the above example, it’s good to check that the operation you are going to do at least has a chance of succeeding. So there is still an
if ()check, followed by the appropriate exception handling logic.