Exception Handling in C#
Exceptions are the standard mechanism in C# for signaling that something went wrong during execution — invalid input, an unavailable resource, a violated invariant — in a way that unwinds the call stack until code that knows how to handle it is reached, or the program terminates if nothing does. Every exception is an object deriving ultimately from System.Exception, carrying a Message, a StackTrace, and often an InnerException chaining back to an underlying cause. The try/catch/finally structure lets you isolate risky code, react to specific failure types, and guarantee cleanup regardless of whether an exception occurred.
Cricket analogy: When a batter is given out lbw incorrectly, the umpire's decision unwinds up the review chain to the third umpire until someone with the authority to overturn it steps in, just as an exception unwinds the call stack.
try, catch, and finally
Code that might throw goes inside a try block. One or more catch blocks follow, each specifying an exception type (or a filter with when) to handle; the runtime picks the first catch clause whose type matches the thrown exception, checked top to bottom, so more specific exception types must be listed before more general ones. A finally block, if present, always executes — whether the try block completed normally, threw a handled exception, or threw an exception that propagated past all catch clauses — making it the right place for cleanup that must not be skipped, such as releasing unmanaged resources (though using/IDisposable is usually cleaner for that specific case).
Cricket analogy: A bowling attack tries risky yorkers in the try block; specific catch clauses handle a no-ball differently from a wide, checked in order of specificity, while the umpire always resets the field (finally) regardless of outcome.
public static decimal SafeDivide(decimal numerator, decimal denominator)
{
try
{
if (denominator == 0)
throw new DivideByZeroException("Cannot divide by zero.");
return numerator / denominator;
}
catch (DivideByZeroException ex)
{
Console.Error.WriteLine($"Math error: {ex.Message}");
throw; // re-throw preserving the original stack trace
}
catch (Exception ex) when (ex.Message.Contains("overflow"))
{
// Exception filter: only catches exceptions matching the condition
Console.Error.WriteLine("Overflow detected during division.");
return 0m;
}
finally
{
Console.WriteLine("SafeDivide attempt completed.");
}
}
try
{
SafeDivide(10m, 0m);
}
catch (DivideByZeroException)
{
Console.WriteLine("Caller handled the propagated exception.");
}throw vs throw ex, and the Exception Hierarchy
Inside a catch block, a bare throw; re-raises the current exception while preserving its original stack trace, whereas throw ex; resets the stack trace to the current location, hiding where the error actually originated — almost always the wrong choice when re-throwing. Common built-in exception types include ArgumentException (and its more specific siblings ArgumentNullException, ArgumentOutOfRangeException), InvalidOperationException for calling a method when an object is in the wrong state, and NullReferenceException, which signals a dereferenced null reference and should generally be prevented via nullable reference types and guard clauses rather than caught.
Cricket analogy: A captain relaying an umpire's original decision word-for-word to the broadcaster preserves the true call, but if he paraphrases it as his own opinion, viewers lose track of who actually made the original ruling on the field.
Exceptions in .NET are relatively expensive to throw compared to normal control flow, due to stack unwinding and stack trace capture. They should represent truly exceptional conditions, not routine control flow — for example, prefer TryParse-style APIs (int.TryParse) over catching a FormatException for expected invalid input.
Catching System.Exception broadly (catch (Exception ex)) without a specific reason swallows unrelated bugs — including things like NullReferenceException or OutOfMemoryException that usually indicate a real defect — and makes debugging much harder. Catch the most specific exception type you can meaningfully recover from.
- try/catch/finally structures isolate risky code, handle specific exception types, and guarantee cleanup.
- catch clauses are matched top to bottom by type, so specific exception types must precede general ones like Exception.
- finally always runs, whether or not an exception was thrown or caught.
- A bare throw; inside a catch preserves the original stack trace; throw ex; resets it and should be avoided.
- Exception filters (catch (T ex) when (condition)) let you conditionally handle exceptions without losing type specificity.
- Exceptions should represent exceptional conditions, not routine control flow — prefer TryParse-style APIs when failure is expected and common.
Practice what you learned
1. In what order are multiple catch clauses evaluated when an exception is thrown?
2. What is the key difference between 'throw;' and 'throw ex;' inside a catch block?
3. When does a finally block execute?
4. What does an exception filter (catch (Exception ex) when (condition)) allow you to do?
5. Why is catching System.Exception broadly, without a specific reason, generally discouraged?
Was this page helpful?
You May Also Like
Custom Exceptions
Custom exception types let you model domain-specific failure conditions precisely, carrying extra context and enabling callers to catch them selectively.
using and IDisposable
Learn how .NET manages unmanaged resources through the IDisposable pattern and how the using statement and using declarations guarantee deterministic cleanup.
Nullable Reference Types
See how C# 8's nullable reference types add compile-time null-safety annotations on top of the runtime's existing nullable value type system.
Common C# Pitfalls
A tour of the mistakes that trip up C# developers most often — from closures over loop variables to silent null reference bugs and misused async void.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics