Exceptions: try, catch, finally and throw
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
When things go wrong at runtime
The compiler catches typing mistakes. It cannot catch a missing file, a network failure or a user who types "abc" where a number is needed. Those problems happen while the program runs. In C# they are reported as exceptions. If nobody handles an exception, the program stops and prints a stack trace.
try, catch, finally
Put the risky code in a try block. Follow it with one or more catch blocks for the problems you can deal with. A finally block runs whatever happens, which is the place for cleanup.
Console.Write("Enter a number to divide 100 by: ");
string? text = Console.ReadLine();
try
{
int divisor = int.Parse(text!);
int result = 100 / divisor;
Console.WriteLine($"100 / {divisor} = {result}");
}
catch (FormatException)
{
Console.WriteLine("That was not a whole number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("You cannot divide by zero.");
}
catch (OverflowException)
{
Console.WriteLine("That number is too large.");
}
finally
{
Console.WriteLine("Calculation finished.");
}
// Throwing our own exception
try
{
Withdraw(balance: 500m, amount: 800m);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine($"{ex.Message} Short by {ex.Shortfall:N2}.");
}
static decimal Withdraw(decimal balance, decimal amount)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive.");
}
if (amount > balance)
{
throw new InsufficientFundsException(amount - balance);
}
return balance - amount;
}
class InsufficientFundsException : Exception
{
public decimal Shortfall { get; }
public InsufficientFundsException(decimal shortfall)
: base("Not enough money in the account.")
{
Shortfall = shortfall;
}
}
Walking through it
Three different things can go wrong in the first block. int.Parse can throw FormatException if the text is not a number, and OverflowException if it is too large for an int. The division can throw DivideByZeroException. Each has its own catch, with its own helpful message. C# runs the first matching catch only.
The exclamation mark in text! silences the null warning, since a null here would throw an ArgumentNullException that nobody catches. In a real program, check for null first.
The finally block prints its message in every case: success, handled error or unhandled error. Typical uses are closing files and releasing connections. You will often see using statements used for this instead, as in the next lesson.
Next, Withdraw uses throw to signal bad input or an impossible request. I used the built-in ArgumentOutOfRangeException for the first and a custom InsufficientFundsException for the second. A custom exception class inherits from Exception and can carry extra data. Here it carries the shortfall, so the caller can show it.
Rules I follow
- Catch only what you can handle. If you cannot recover, let it travel up to a place that can.
- Catch specific types first. A catch for
Exceptioncatches everything, so it goes last, if at all. - Never write an empty catch block. Swallowing errors hides bugs for months.
- Use
throw;to rethrow, notthrow ex;. The first keeps the original stack trace. The second resets it. - Do not use exceptions for normal flow. If bad input is expected, use
TryParse. Exceptions are slow compared to a simple check, and they make the code harder to follow.
Reading a stack trace
When a program crashes, read the stack trace from the top. The first line names the exception and message. The next lines show which methods were running, newest first. Find the first line that points to your own file and line number. That is where to look.
Common mistakes
- Catching
Exceptioneverywhere and printing "something went wrong". - Losing the original error when wrapping. Pass it as the inner exception:
throw new MyException("text", ex);. - Putting too much in the try block. Keep it small so you know which line failed.
Try it yourself
- Write a program that asks for two numbers and divides them, handling all three problems from the example without crashing.
- Rewrite it using
TryParseand aniffor zero. Which version is shorter? - Create a
InvalidAgeExceptionand throw it from a method that sets a person's age when it is outside 0 to 130.
Console.Write("Enter a number to divide 100 by: ");
string? text = Console.ReadLine();
try
{
int divisor = int.Parse(text!);
int result = 100 / divisor;
Console.WriteLine($"100 / {divisor} = {result}");
}
catch (FormatException)
{
Console.WriteLine("That was not a whole number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("You cannot divide by zero.");
}
catch (OverflowException)
{
Console.WriteLine("That number is too large.");
}
finally
{
Console.WriteLine("Calculation finished.");
}
// Throwing our own exception
try
{
Withdraw(balance: 500m, amount: 800m);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine($"{ex.Message} Short by {ex.Shortfall:N2}.");
}
static decimal Withdraw(decimal balance, decimal amount)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive.");
}
if (amount > balance)
{
throw new InsufficientFundsException(amount - balance);
}
return balance - amount;
}
class InsufficientFundsException : Exception
{
public decimal Shortfall { get; }
public InsufficientFundsException(decimal shortfall)
: base("Not enough money in the account.")
{
Shortfall = shortfall;
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account