Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 182 ยท Null Safety and Errors

Exceptions

Learn C# exception handling - try/catch/finally, the exception hierarchy, catch order, throw versus throw ex, stack traces, finally ordering, unhandled exceptions and exit codes, with runnable examples.

Programs meet situations they cannot handle in the normal flow: a file is missing, a number cannot be parsed, an index is out of range, the network is gone. C# reports these with exceptions. An exception is an object describing what went wrong; when code throws it, normal execution stops, and the runtime walks back up the call stack looking for a catch block that can handle it. If it finds none, the program ends.

This lesson builds the mental model first (what "unwinding" means), then walks through try, catch, finally, the exception class hierarchy, the order of catch blocks, the important difference between throw; and throw ex;, what a stack trace tells you, and what happens when nobody catches an exception.

Your first exception

C# An unhandled exception (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The array has three elements, so index 5 is invalid. The runtime creates an IndexOutOfRangeException, and since no code catches it, the program prints Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array. followed by a stack trace, and stops. "never printed" really never prints. That is the default behavior and it is good: crashing loudly beats continuing with corrupt state.

try and catch

To handle the problem, put the risky code in a try block and the recovery in a catch block:

C# Catching an exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Four things to notice:

  1. The try block runs until something throws. The rest of that block is skipped.
  2. Control jumps to the first catch whose type matches the thrown exception (or a base class of it).
  3. After the catch block finishes, execution continues after the whole try statement. The loop carries on with the next input.
  4. Each exception carries a Message (human-readable), a StackTrace, an optional InnerException, and often extra data like ParamName.

catch (FormatException e) declares e only if you use it. If you do not need the object, write catch (FormatException). A bare catch { } catches everything, which is almost never what you want.

The exception hierarchy

All exceptions derive from System.Exception. The tree below shows the ones you will meet most:

TEXT
Exception
โ”œโ”€โ”€ SystemException
โ”‚   โ”œโ”€โ”€ ArgumentException
โ”‚   โ”‚   โ”œโ”€โ”€ ArgumentNullException
โ”‚   โ”‚   โ””โ”€โ”€ ArgumentOutOfRangeException
โ”‚   โ”œโ”€โ”€ InvalidOperationException
โ”‚   โ”‚   โ””โ”€โ”€ ObjectDisposedException
โ”‚   โ”œโ”€โ”€ NullReferenceException
โ”‚   โ”œโ”€โ”€ IndexOutOfRangeException
โ”‚   โ”œโ”€โ”€ InvalidCastException
โ”‚   โ”œโ”€โ”€ FormatException
โ”‚   โ”œโ”€โ”€ ArithmeticException
โ”‚   โ”‚   โ”œโ”€โ”€ DivideByZeroException
โ”‚   โ”‚   โ””โ”€โ”€ OverflowException
โ”‚   โ”œโ”€โ”€ NotSupportedException
โ”‚   โ””โ”€โ”€ IOException (System.IO)
โ”‚       โ””โ”€โ”€ FileNotFoundException, DirectoryNotFoundException
โ”œโ”€โ”€ ApplicationException   (legacy; do not derive from it)
โ””โ”€โ”€ your own exceptions (see the next lessons)

Because catch (ArgumentException) also matches ArgumentNullException, the hierarchy lets you choose how specific to be.

C# Catching by base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Every line was caught by one of the three catch blocks; DivideByZeroException matched ArithmeticException, ArgumentNullException matched ArgumentException, and the rest fell through to SystemException.

Order of catch blocks

The runtime checks catch blocks top to bottom and uses the first match. So more specific types must come first. If a base class comes before a derived class, the derived catch could never run, and the compiler refuses:

C# Wrong catch order (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('Exception'). Put the narrow catches first, general ones last, and think hard before writing the general one at all.

finally: code that always runs

A finally block runs whether the try succeeded, threw, or exited early through return, break or goto. It is the place for cleanup that must happen.

C# Following the flow through try, catch and finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In both runs "finally runs last" appears after the code that chose the return value but before the caller sees it. The return value is computed first, then the finally block runs, then the method actually returns.

For disposable resources prefer using, which is a try/finally written for you (see IDisposable, using and Finalizers). Do not return, break or throw from inside finally; it silently replaces whatever was in flight.

Nested calls and unwinding

When an exception is not caught in the method that throws it, the runtime unwinds the stack: it leaves that method (running its finally blocks) and looks in the caller, and so on.

C# Unwinding through three methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Output order shows the finally blocks running from the innermost outward, before the catch in Main prints (the runtime first finds the handler, then unwinds running finally blocks, then enters the catch).

throw versus throw ex

Sometimes you want to catch an exception, do something (log it, clean up) and let it continue. There are two ways to rethrow, and they are not equal.

  • throw; rethrows the same exception and keeps its original stack trace.
  • throw ex; throws the same object again but resets the stack trace to this point, hiding where the problem really started.
C# Rethrow that keeps the trace and one that loses it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

With throw; the trace contains Demo.Fail, the place that really threw. With throw ex; the trace starts at Demo.Wrap; the true origin is gone. The compiler analyzers flag throw ex; (CA2200) for that reason. If you want to add context, wrap the original as an InnerException of a new exception instead:

C# Wrapping with an inner exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Reading a stack trace

When an exception goes unhandled, the output has two parts: the type and message, then the stack trace, one line per active method, innermost first. Read it from the top: the first line with your file name and a line number is usually where to look.

TEXT
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
   at Program.Average(Int32 total, Int32 count) in main.cs:line 9
   at Program.<Main>$(String[] args) in main.cs:line 3

Average was running, called from the top-level code at line 3. Line numbers are available when debug symbols exist (always in our editor). Exceptions are also expensive compared to normal returns, because the runtime must capture the trace and unwind. That is fine for rare failures and wrong for "expected" outcomes like a user typing letters into a number field, where int.TryParse is the better tool (see Exception Filters and Error Handling Patterns).

Unhandled exceptions and exit codes

If no catch handles an exception, .NET prints it to standard error and ends the process abnormally. On a normal run, Main returns 0 (success) or the int it returns; a crashed process gets a non-zero code decided by the operating system (on Linux a SIGABRT signal, 134 in a shell; on Windows the code 0xE0434352). Scripts and CI systems read that code to decide whether the job failed.

You choose the exit code for expected failures by returning it from Main or setting Environment.ExitCode:

C# Choosing an exit code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

By convention 0 means success and small positive numbers mean specific failures (2 for bad usage, for example). Your program stays in charge instead of crashing with a stack trace in front of a user.

Practical rules

  • Catch only what you can handle. If you cannot fix it or add useful context, let it propagate.
  • Catch specific types and put the narrowest first. Avoid catch (Exception) except at the outermost layer (a request pipeline, a main loop) where you log and fail gracefully.
  • Never swallow exceptions with an empty catch. At least log them.
  • Use throw; to rethrow, never throw ex;.
  • Do not use exceptions for normal control flow; they are for exceptional conditions.
  • Clean up in finally or using, not at the end of the try.
  • Some exceptions (OutOfMemoryException, StackOverflowException) cannot be meaningfully recovered from; a stack overflow ends the process outright.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A try block throws FormatException. There are two catch blocks, first catch (Exception) then catch (FormatException). What happens?

    A catch for a base type before a derived type makes the second unreachable, so the compiler rejects it. Order catch blocks from specific to general.
  2. 2. What is the difference between throw; and throw ex; inside a catch block?

    throw; rethrows the active exception unchanged, including where it came from. throw ex; restarts the stack trace at the current line.
  3. 3. When does a finally block run?

    finally is for cleanup that must always happen. It runs on normal completion, after a handled or propagating exception and on early exits such as return.
  4. 4. Which exception does catch (ArgumentException) also catch?

    ArgumentNullException derives from ArgumentException, so a catch for the base type matches it.
  5. 5. What should you do with an exception you cannot handle meaningfully in the current method?

    Swallowing hides bugs. Catch only what you can handle or add context to, and let the rest travel up to code that knows what to do.

Summary

  • An exception is an object thrown to signal an error; the runtime unwinds the stack to find a matching catch, running finally blocks on the way.
  • catch blocks are tested top to bottom; put specific types first (a base type before a derived one is compile error CS0160).
  • finally always runs, after the return value is computed and before the caller receives it.
  • Rethrow with throw; to preserve the stack trace; wrap in a new exception with an InnerException to add context.
  • Unhandled exceptions print a stack trace and end the process with a non-zero code; for expected failures return your own exit code.
  • Catch only what you can handle, never swallow silently, and prefer TryParse-style methods for common failures.

Next: Custom Exceptions and Exception Design