← Retour au cours: C# from scratch

Exceptions, try/catch/finally and week review

Vidéo bientôt disponible

Real programs fail: the file does not exist, the network drops, the user types letters where you expected a number, someone divides by zero. When something like this happens, .NET creates an exception, an object that describes the problem, and interrupts the normal flow. If nobody handles it, the program ends with an ugly message. The try/catch mechanism lets you capture the error, decide what to do and keep running gracefully.

try, catch and finally

In the try block you write the code that may fail. If it throws an exception, execution jumps to the first catch whose type matches. You can have several catch blocks, from the most specific to the most general; the last one usually catches Exception, which is the parent of all. The exception variable offers Message with the description and StackTrace with the path. The finally block always runs, whether or not there was an error, and is used to release resources. A when clause lets you filter a catch with a condition.

csharp
Console.WriteLine(SafeDivide(10, 2));    // Division finished, then 5
Console.WriteLine(SafeDivide(10, 0));    // Cannot divide by zero, Division finished, then 0

int SafeDivide(int a, int b)
{
    try
    {
        return a / b;
    }
    catch (DivideByZeroException)
    {
        Console.WriteLine("Cannot divide by zero");
        return 0;
    }
    finally
    {
        Console.WriteLine("Division finished");   // always runs
    }
}

try
{
    int[] data = [1, 2, 3];
    Console.WriteLine(data[5]);
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine($"Index problem: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected: {ex.Message}");
}

Throwing your own exceptions

You can also throw exceptions with throw when you detect something invalid. For wrong arguments use ArgumentException or ArgumentNullException; for operations not allowed in the current state, InvalidOperationException. If you need an error of your own, create a class that inherits from Exception, with a clear message. A key tip: exceptions are for exceptional situations, not for normal flow. Do not use try/catch to check whether a text is a number; for that there is TryParse, which is faster and clearer. And never catch an exception and silently ignore it with an empty catch: hiding errors is worse than seeing them.

csharp
var account = new Account(100m);
try
{
    account.Withdraw(30m);
    Console.WriteLine(account.Balance);    // 70
    account.Withdraw(500m);                // throws
}
catch (InsufficientFundsException ex)
{
    Console.WriteLine($"{ex.Message} (missing {ex.Missing})");
    // Not enough money (missing 430)
}

try
{
    account.Withdraw(-5m);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ParamName);       // amount
}

class InsufficientFundsException(decimal missing) : Exception("Not enough money")
{
    public decimal Missing { get; } = missing;
}

class Account(decimal initial)
{
    public decimal Balance { get; private set; } = initial;

    public void Withdraw(decimal amount)
    {
        if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        if (amount > Balance) throw new InsufficientFundsException(amount - Balance);
        Balance -= amount;
    }
}

Testez vos acquis

Question 1 sur 6

When does the finally block run?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →