Exceptions and error boundaries
Exceptions and error boundaries
An exception interrupts normal execution when an operation cannot complete as intended. A throw statement signals the failure; a compatible catch can handle it. Use a boundary where the program knows how to recover, report a useful error or translate the failure. Common invalid input is usually better handled by validation than by exceptions.
using System;try{ Console.WriteLine("Start"); Reserve(0); Console.WriteLine("Reserved");}catch (ArgumentOutOfRangeException){ Console.WriteLine("Invalid quantity");}Console.WriteLine("Continue");static void Reserve(int quantity){ if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));}Reserve signals an invalid argument. The catch runs; Reserved is skipped, and execution resumes after the handler. nameof(quantity) supplies the parameter name.
Expected output (reasoned, not executed):
StartInvalid quantityContinueTrace the exceptional path
Statements in a try block run until completion or an exception interrupts them. The runtime searches for a compatible catch, possibly in a calling method. Code after the failing operation in that try block is skipped. Catch more specific exception types before broader ones when both could match. A catch is optional if a try has a finally. Under normal control flow and ordinary exception unwinding, finally runs when leaving its associated try/catch, including on return; abrupt process termination is not covered by this guarantee.
Choose where to recover
An argument outside the documented domain can justify ArgumentOutOfRangeException. A failed operation due to current object state can justify InvalidOperationException. Do not catch Exception merely to hide problems. If a catch cannot recover, use throw; inside it to rethrow while preserving the original stack trace; avoid throw ex; as a routine rethrow. A filter when (condition) can select whether a catch handles an exception. Keep user-facing messages useful and do not disclose secrets or internal stack traces to users. Use TryParse for routine conversion failure in the next lesson.
using System;try{ Console.WriteLine("Open"); throw new InvalidOperationException("Synthetic failure");}catch (InvalidOperationException){ Console.WriteLine("Handle");}finally{ Console.WriteLine("Cleanup");}Console.WriteLine("Done");The finally block runs after the matching catch and before control leaves the statement. This example logs a synthetic cleanup event, not an actual resource release.
Expected output (reasoned, not executed):
OpenHandleCleanupDoneusing System;try{ Process();}catch (InvalidOperationException){ Console.WriteLine("Operation unavailable");}static void Process(){ try { throw new InvalidOperationException("Synthetic failure"); } catch (InvalidOperationException) { Console.WriteLine("Record failure"); throw; }}The inner catch records a failure but does not claim recovery. The outer boundary receives the same exception. The example uses fixed public messages.
Expected output (reasoned, not executed):
Record failureOperation unavailableCommon mistakes
Never use an empty catch to make errors disappear. It can leave the program reporting success after a failed operation. Catch a known recoverable exception, produce a meaningful result, or let the failure propagate. Avoid returning or throwing from cleanup code in a way that obscures the original error.
Practice
Write a CheckCapacity method accepting a requested count and available count. Assume both are nonnegative. Throw InvalidOperationException when requested exceeds available. Catch at the caller and print either Accepted or Not enough capacity. Test (2, 5), (5, 5), (6, 5).
Predict the outcome before checking your work. The separate manual practice and quiz are staged, not automatically graded.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exceptions and error boundaries — knowledge check
Apply the lesson concepts to the following scenarios.
What happens to statements after a throw in the same try block?
Which exception should be caught first if both specific and broad catches are unfiltered?
When does finally execute in ordinary exception unwinding?
Which statement rethrows the current exception and preserves its original stack trace?
What is best for ordinary invalid numeric input?