Handling errors and exceptions in C#

It is very difficult to ensure that a piece of code always works as expected. Failures can occur for a large number of reasons, many of which are beyond your control as a programmer. Any applications that you write must be capable of detecting failures and handling them in a graceful manner.

✓ Try and catch mechanism
Write your code within a try block. When the code runs, it attempts to execute all the statements in the try block, and if none of the statements generates an exception, they all run, one after the other, to completion. However, if an error condition occurs, execution jumps out of the try block and into another piece of code designed to catch and handle the exception.

try
{
    int leftHandSide = int.Parse(lhsOperand.Text);
    int rightHandSide = int.Parse(rhsOperand.Text);
}
catch (FormatException fEx)
{
    result.Text = fEx.Message;
}

When a FormatException is thrown, the fEx variable is populated with an object containing the details of the exception. Message property contains a text description of the error that caused the exception.

✓ Unhandled Exceptions – If the calling method does not use a try block or there is no matching catch handler, the calling method immediately exits and execution returns to its caller, where the process is repeated. If a matching catch handler is eventually found, the handler runs and execution continues with the first statement that follows the catch handler in the catching method.

✓ Using multiple catch handlers

try
{
    ...
}
catch (FormatException fEx)
{
    result.Text = fEx.Message;
}
    catch (OverflowException oEx)
{
    result.Text = oEx.Message;
}

✓ Throwing exceptions

switch (month)
{
    case 1 :
        return “January”;
    case 2 :
        return “February”;
    ...
    case 12 :
        return “December”;
    default :
        throw new ArgumentOutOfRangeException(“Bad month”);
}

In above example, what should the method return if the integer argument is less than 1 or greater than 12? The method shouldn’t return anything at all and it should throw an exception. This new excemption needs to caought by catch.

✓ Catching unhandled exceptions – All hitherto unhandled exceptions can be caught using below catch handler

catch (Exception ex)
{
    result.Text = ex.Message;
}

✓ Using finally block

TextReader reader = ...;
...
try
{
string line = reader.ReadLine();
while (line != null)
{
...
line = reader.ReadLine();
}
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}

In above example, even if an exception occurs while reading the file, the finally block ensures that the reader.Dispose statement always executes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s