Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if-condition vs exception handler

Tags:

c#

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?

like image 949
Nemo Avatar asked Dec 31 '11 08:12

Nemo


People also ask

Why do we use exception handling instead of if-else?

Using exceptions makes handling errors much more easy - you just assume that if something goes wrong - the other code will throw exception, so you just wrap the code in try block and handle possible exception on your own way.

Is if-else better than try catch?

You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it.

How is try catch different than if-else?

In 'try-catch' the codes to handle the exceptions and what exception to be handled, that are easily readable. In 'if-else', we have one else block corresponding to one if block. Or we need to define another condition with command 'else if'. In 'try-catch' we don't have to define each 'try' block with a 'catch' block.

Is try except faster than if?

Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code.


1 Answers

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":

Do not use exceptions for normal flow of control, if possible. Except for system failures and operations with potential race conditions, framework designers should design APIs so that users can write code that does not throw exceptions. For example, you can provide a way to check preconditions before calling a member so that users can write code that does not throw exceptions.

Here is an example of a bad practice where an exception is handled but can nearly always be avoided:

public int? GetItem(int index)
{
    int? value = null;
    try
    {
        value = this.array[index];
    }
    catch (IndexOutOfRangeException)
    {
    }

    return value;
}

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:

public int? GetItem(int index)
{
    int? value = null;

    // Ensure the index is within range in the first place!
    if (index >= 0 && index < this.array.Length)
    {
        value = this.array[index];
    }

    return value;
}

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:

public void Close()
{
    // Attempt to avoid exception by doing initial state check
    if (this.channel.State == CommunicationState.Opened)
    {
        try
        {
            // Now we must do a (potentially) remote call;
            // this could always throw.
            this.channel.Close();
        }
        catch (CommunicationException)
        {
        }
        catch (TimeoutException)
        {
        }
    }

    // If Close failed, we might need to do final cleanup here.
    if (this.channel.State == CommunicationState.Faulted)
    {
        // local cleanup -- never throws (aside from catastrophic situations)
        this.channel.Abort();
    }
}

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.

like image 186
bobbymcr Avatar answered Oct 23 '22 06:10

bobbymcr