if-condition vs exception handler
Asked Answered
I

5

21

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?

Intracellular answered 31/12, 2011 at 8:10 Comment(1)
'The interviewer seemed to be expecting some other answer' - then why didn't you ask him? I am alway more impressed by a question than by an answer when interviewing...Toupee
T
26

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.

Thurstan answered 31/12, 2011 at 8:51 Comment(2)
In your 'GetItem' example, the caller is unable to determine if an invalid index was supplied, or if array[index] contains a null value. So the question remains what is better. Should you throw an exception if an invalid index was used? Or will you just return a null value without any indication that an error occured? Using an invalid index on an array will also cause an exception, it will not return the default value of the array type!Beckon
@comecme: In that example, you can assume array was declared as int[], so null can only mean that the value does not exist (out or range). Yes, the caller won't know, but the implementer will know and should not use exceptions as control flow which was the point of the example. It is valid to return a default value without throwing an exception, although this pattern is generally expected to be expressed in a TryXxx method, as discussed here: msdn.microsoft.com/en-us/library/ms229009.aspxThurstan
D
10

Exception handling is a heavy and expensive operation as far as performance is concerned. If you can avoid catching an exception by using proper if else that can increase application's performance

On the other hand if else block makes more sense to code reader. They are easy to understand and maintain as compared to exceptional try catch block. They describe the program flow in more elegant manner

And finally as you said Exception handling should be for uncertain situations or for exceptional cases it should not be the default choice

Edit

A common bad practise I have seen at some places is this

 try
 {
     string str = "Some String"
     int i = Convert.ToInt32(str);
 }
 catch (Exception ex)
 {
      MessageBox.Show("Invalid input");          
 }

Now try catch can be easily avoided in this casing by using if else

  string str = "Some String"
  int i;
    if(!int.TryParse(str, out i))
    {
       MessageBox.Show("Invalid input");          
    }
Dowery answered 31/12, 2011 at 8:14 Comment(1)
Normally the class converting the string wouldn't be the class displaying error messages. That's why exceptions exist: they can be catched on a higher level.Beckon
A
4

The correct answer is just the one that you gave.

For greater specificity, you should've said something to the effect of "I use if statements wherever possible due to the overhead of catching and throwing exceptions".

Alidus answered 31/12, 2011 at 8:14 Comment(0)
M
2

I normally prefer to use some special undefined value (e.g. null for objects) to indicate that some computation could not produce a valid result because of invalid input. This means that my code could successfully determine and report that the input data is invalid and no meaningful result can be produced.

I prefer to use an exception when my code cannot complete the requested computation, e.g. if a file containing some required data does not exist, if it cannot connect to a database.

So conceptually:

  • Undefined result (plus if-condition): program successfully determines that there is no valid output for the given input.
  • Exception (plus try-catch): program cannot complete computation due to some error in the application not related to the input.
Microgamete answered 31/12, 2011 at 11:38 Comment(0)
E
0

If you know the exact login of the program and knows the errors that can occur then you can write if-else statement or in other case you can leave things to try catch exception handling.

Estop answered 31/12, 2011 at 8:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.