4.1.1.9 - Exceptions and defensive input (C#)

4.1.1.9 - Exceptions and defensive input (C#)

Input and external operations can fail even when a program's intended algorithm is sound. Learn what an exception does to control flow, how specific handlers report failure, and how validation and recovery keep a program in a safe state.

C# route status: incomplete: runnable support pending. These examples and answers are written native C# with no Run control; complete onscreen Paper 1 preparation still requires runnable support.

Exceptional conditions

An exception interrupts the normal sequence of execution when an operation cannot complete normally.

Exception

A runtime event represented by an exception object that transfers control away from the failing operation to an applicable handler, or terminates execution if it is unhandled.

int.Parse("apple") raises FormatException because the text is not an integer. An integer outside the representable range raises OverflowException. Integer division by zero raises DivideByZeroException. An invalid array index raises IndexOutOfRangeException. These examples are not syntax errors: valid source can still fail for particular data.

Within a try block, an exception skips the remaining statements in that block. A matching catch handles it; execution can then continue after the try/catch structure. Without an applicable handler it propagates to a caller and can terminate the program.

C#
try
{
    int count = int.Parse("apple");
    Console.WriteLine(count + 1);
}
catch (FormatException)
{
    Console.WriteLine("Enter a whole number.");
}
Console.WriteLine("Finished");

With using System; and this fragment inside Main, the output lines are Enter a whole number. and Finished. The failed assignment never produces a usable count; the line adding one is skipped. A runtime exception differs from a logic error, such as using the wrong discount rate while the program runs without interruption.

Handling and reporting errors

A useful handler addresses the actual failure and gives a recovery message that the user can act on.

This fragment treats a malformed integer differently from an integer too large for int:

C#
try
{
    int quantity = int.Parse(input);
    Console.WriteLine("Quantity: " + quantity);
}
catch (FormatException)
{
    Console.WriteLine("Use whole-number digits.");
}
catch (OverflowException)
{
    Console.WriteLine("Number outside the integer range.");
}

It assumes input is a supplied non-null string. Only the applicable catch executes. Specific handlers avoid misreporting every failure as invalid text: an unrelated programming defect should not automatically be swallowed. If a broad catch (Exception) is used, it must follow more specific catches; otherwise those later catches cannot be reached. Do not invent an apparently successful output after a failed operation.

A finally block executes when control leaves the associated try/catch, whether normal completion or an exception occurred in ordinary execution. It is useful for cleanup, such as closing a resource. It is not a success-only branch. Modern C# resource handling often uses using, but detailed file/resource work belongs in the files lesson.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account