Exceptions
try, catch, finally
An exception is how a method reports that it cannot do its job. It carries a type, a message and an optional inner exception, and it unwinds the stack until some catch accepts it. The three blocks are the whole statement:
- try holds the code that may throw.
- catch (Type name) runs when an exception of that type, or of a type derived from it, reaches the block.
- finally runs whether the try succeeded, threw or was left through a return.
try
{
Console.WriteLine("try");
throw new InvalidOperationException("broken");
}
catch (InvalidOperationException e)
{
Console.WriteLine($"caught {e.Message}");
}
finally
{
Console.WriteLine("finally");
}
Console.WriteLine("after");
dotnet run
try
caught broken
finally
after
The lines are in source order and prove the rule: the try body ran until the throw, the catch took over, the finally ran after the catch, and execution continued after the whole statement. The program exited with 0, because the exception was handled.
The order of the blocks
Only one catch block runs per exception, and the first one whose type matches wins. That is why the compiler refuses a catch of a base type before a catch of a derived type, with error CS0160: the second block could never run. In practice:
- The runtime searches the catch blocks in the order written and picks the first match; Exception matches everything.
- A finally block runs on the way out, before the exception continues to the next frame.
- A catch without a type is allowed and means catch (Exception); this course always writes the type.
- throw; inside a catch rethrows the same exception with its original stack trace, which is the way to log and let it continue.
More than one catch
int.Parse can fail in two different ways, and the two exceptions are different types. A caller that cares about the difference writes two catches:
Console.WriteLine("reports");
Report("12");
Report("abc");
Report("99999999999999999999");
static void Report(string text)
{
try
{
Console.WriteLine(int.Parse(text));
}
catch (FormatException)
{
Console.WriteLine($"format [{text}]");
}
catch (OverflowException)
{
Console.WriteLine($"overflow [{text}]");
}
}
dotnet run
reports
12
format [abc]
overflow [99999999999999999999]
The text that is not a number threw FormatException; the number that does not fit in an int threw OverflowException. Both are separate classes, so a catch of FormatException alone would not have caught the second one.
The finally of a method that throws
A finally belongs to the frame that declared it, so it runs while the exception travels out of that method, before the caller catches it:
try
{
Console.WriteLine(WithFinally());
}
catch (Exception e)
{
Console.WriteLine($"caught outer: {e.Message}");
}
Console.WriteLine("done");
static string WithFinally()
{
try
{
throw new Exception("inner");
}
finally
{
Console.WriteLine("finally runs");
}
}
dotnet run
finally runs
caught outer: inner
done
finally runs printed first, although the throw is the last statement of the inner method: the runtime left the method through its finally block on the way to the caller, and the outer catch then continued to the line after it. This is why a resource is released in finally, and why the using statement later in this part compiles to exactly that.
Exercises
- Put return inside the try block of the first program and confirm that the finally still runs.
- Add a catch (Exception e) before the two typed catches and read CS0160.
- Replace throw new Exception("inner") with throw; in a catch and compare the stack trace.
- Catch nothing in Report and look at the program output; the next lesson on unhandled exceptions explains the exit status.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which catch block runs when an exception is thrown?
Answer
The first one whose type matches, in source order
The runtime searches in order, which is why a base catch before a derived one is CS0160.
-
When does a finally block run?
Answer
Whether the try succeeded, threw, or left through return
finally is the unconditional part, which is what makes it the place for cleanup.
-
What does this program print?
try { throw new Exception("a"); } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("f"); }Answer
a and then f
The catch handles the exception and the finally runs after it.
-
Which exception does
int.Parse("abc")throw?Answer
FormatException
The text is not a number in the expected format, which is what FormatException reports.
-
What does
int.Parse("99999999999999999999")throw?Answer
OverflowException
The digits are valid but the value does not fit in an int, so the parse overflows.
-
What does this program print?
try { Console.WriteLine("t"); } catch { Console.WriteLine("c"); } finally { Console.WriteLine("f"); }Answer
t and then f
No exception was thrown, so the catch is skipped and the finally still runs.
-
What does
throw;inside a catch do?Answer
Rethrows the same exception with its original stack trace
The bare throw keeps the exception object and its trace, unlike throw e.
-
Why does a finally block run before the caller catches?
Answer
It belongs to the frame the exception is leaving
Leaving a frame runs its finally blocks before the exception reaches the caller.
-
What does a handled exception do to the exit status?
Answer
Nothing, the program still exits with 0
A catch is a normal return path, so the process continues and ends with its own status.
-
Which is the correct order of the blocks?
Answer
try, catch, finally
The try body comes first, then the handlers, then the unconditional block.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev