Learn/C#/9. Handling errors
Lesson 9 of 15
Sign in

C#, lesson 9

Handling errors

Things go wrong: someone types ten where you expected 10, a file is missing, an amount is negative. .NET reports problems like these with exceptions. When an operation fails, it throws an exception object and normal execution stops. The runtime then looks back through the methods that are currently running for a catch block that handles that type of exception. If it finds none, the program ends with an error message and a stack trace.

try, catch and finally

When int.Parse throws, control jumps straight to the first matching catch, skipping the rest of the try block. The finally block runs whether or not anything failed, so it is the place for cleanup. You can stack several blocks, most specific first, and give the exception a name to inspect it: .

2 exercises to try what you just read.

Exercise 1

Forgiving sum

Press Ctrl Enter or Check to test your code.

Exercise 2

Careful cash machine

Press Ctrl Enter or Check to test your code.

catch
catch (OverflowException ex) { Console.WriteLine(ex.Message); }

A when clause adds a condition to a catch, called an exception filter:

Unlike Java, C# has no checked exceptions: the compiler never forces you to catch anything. It is up to you to know what a method can throw (the documentation lists it) and to catch only what you can actually handle.

TryParse: no exception needed

Bad user input is not exceptional; it is expected. For that case .NET offers the Try pattern: a method that returns bool for success and hands back the value through an out parameter.

It is faster than throwing and catching, and the code reads more clearly. Use TryParse for input, TryGetValue for dictionaries, and save try/catch for real failures.

Throwing exceptions

Your own methods should refuse invalid requests loudly, with throw:

Common built-in types are ArgumentException (a bad argument), ArgumentOutOfRangeException (a value outside the allowed range) and InvalidOperationException (the object is not in a state to do that).

For errors that belong to your program's domain, declare your own exception class by deriving from Exception. With top-level statements, type declarations go after all the statements in the file:

That one line uses a primary constructor: the parameter item is passed straight to the base Exception constructor, which stores the message.

using: automatic cleanup

Objects that hold resources, such as files, implement IDisposable. A using declaration disposes of them automatically at the end of the enclosing block, even when an exception is thrown:

Further reading

  • Exceptions and exception handling
  • Exception-handling statements (throw, try)
  • Int32.TryParse

Read lines until the input ends. Each non-blank line should be a whole number that fits in an int, but some lines are garbage. Add up the valid numbers and count the invalid lines; ignore blank lines entirely. Use int.TryParse.

Print Sum: <sum> and Skipped: <count>.

Sample input:

Sample output:

The first line is the starting balance (a whole number). Each following line is a command: deposit <amount> or withdraw <amount>.

The starter declares a custom exception, BankException. Write two local functions:

  • static int Withdraw(int balance, int amount) returns the new balance. It throws a BankException with the message Invalid amount if amount <= 0, or Insufficient funds if amount is larger than the balance.
  • static int Deposit(int balance, int amount) throws Invalid amount if amount <= 0.

For each command, print OK <new balance> or Error: <message>. Finally print Balance: <balance>.

Sample input:

Sample output:

string text = "ten";
try
{
    int n = int.Parse(text);
    Console.WriteLine($"Got {n}");
}
catch (FormatException)
{
    Console.WriteLine($"Not a number: {text}");
}
finally
{
    Console.WriteLine("This always runs");
}
catch (ArgumentException ex) when (ex.Message.Contains("negative"))
if (int.TryParse(text, out int value))
{
    Console.WriteLine($"Doubled: {value * 2}");
}
else
{
    Console.WriteLine("Please type a whole number");
}
static decimal Divide(decimal a, decimal b)
{
    if (b == 0)
    {
        throw new ArgumentException("Cannot divide by zero");
    }
    return a / b;
}
// ... top-level statements above ...

class OutOfStockException(string item) : Exception($"{item} is out of stock");
using var reader = new StreamReader("data.txt");
Console.WriteLine(reader.ReadLine());
10
abc
25

-5
4.5
Sum: 30
Skipped: 2
100
withdraw 30
withdraw 500
deposit -5
deposit 20
OK 70
Error: Insufficient funds
Error: Invalid amount
OK 90
Balance: 90