skip to content

Exceptions and Cleanup

try, catch, finally, exception filters, custom exceptions and using-based disposal: how C# fails and cleans up. Interviewers ask throw vs throw ex and the Dispose pattern.

on this pageshow

explore

questions

21

In C#, which built-in exception should a method throw for a null argument, an out-of-range argument, or a call made in the wrong object state?

level: juniorimportance: must knowfreq 60%

answer

  1. the argument family first
  2. most derived type that fits
  3. object state is not an argument
  4. ParamName names the culprit
  5. runtime-reserved types stay reserved

basics

~10 s

Throw ArgumentNullException for a null argument, ArgumentOutOfRangeException for a value outside the allowed range, and InvalidOperationException when the object's current state forbids the call. Never throw Exception, SystemException or NullReferenceException yourself.

solid answer

~40 s

Bad input belongs to the `ArgumentException` family, and you pick the most derived type that fits: `ArgumentNullException` for `null`, `ArgumentOutOfRangeException` for a value outside the allowed range, plain `ArgumentException` for anything else wrong with an argument, always with `ParamName` set (the `ThrowIfNull`-style helpers set it for you). A call that is valid on its own but wrong for the object's current state, such as quoting before rates are loaded, throws `InvalidOperationException`; a call on a disposed object throws `ObjectDisposedException`; an operation the type does not support throws `NotSupportedException`. Don't throw `Exception`, `SystemException` or `ApplicationException`, which are too general to catch selectively, and leave `NullReferenceException`, `IndexOutOfRangeException` and `AccessViolationException` to the runtime: they signal a bug, so a public method checks its arguments instead of letting them escape. Analyzer rule CA2201 reports both groups.

code

csharp · 32 lines
csharp
var svc = new QuoteService();
Call(() => svc.Quote(null!, 2.5m));
Call(() => svc.Quote("10115 Berlin", -1m));
Call(() => svc.Quote("10115 Berlin", 2.5m));

static void Call(Action call)
{
    try { call(); }
    catch (ArgumentException e)   // also catches ArgumentNullException and ArgumentOutOfRangeException
    {
        Console.WriteLine($"{e.GetType().Name} (ParamName: {e.ParamName})");
    }
    catch (InvalidOperationException e)
    {
        Console.WriteLine($"{e.GetType().Name}: {e.Message}");
    }
}

class QuoteService
{
    private bool _ratesLoaded;
    public void LoadRates() => _ratesLoaded = true;

    public decimal Quote(string address, decimal weightKg)
    {
        ArgumentNullException.ThrowIfNull(address);
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(weightKg);
        if (!_ratesLoaded)
            throw new InvalidOperationException("Rates must be loaded before quoting.");
        return weightKg * 4.2m;
    }
}

go deeper

for a junior

Recall the three everyday types: ArgumentNullException for null, ArgumentOutOfRangeException for a value out of range, InvalidOperationException for the wrong object state. Name at least one type you must never throw.

for a middle

Explain the inheritance: the argument types share ArgumentException and ParamName, ObjectDisposedException derives from InvalidOperationException, and FormatException is not an argument exception. Mention CA2201.

for a senior

Treat the thrown types as part of a public contract: document them, keep them stable across versions, and check arguments so runtime-reserved exceptions never leak from a library's public surface.

for a principal

Decide which analyzer rules a team turns on so the choice of exception type is checked in review, such as enabling CA2201, rather than left to each author's memory.

## Why the exception type is part of the contract A caller reacts to a failure by **catching a type**. If a shipping-quote library throws the same general type for a missing address, a negative parcel weight and a call made before its rate tables were loaded, the caller cannot tell a bug in its own code from a misused object. The .NET design guidelines therefore ask library authors to throw the **most specific existing type** that describes the failure, to document the exceptions a public member throws when its contract is broken, and to keep those types stable from one version to the next. ## The argument family Every exception for a bad argument derives from `System.ArgumentException`, so one `catch (ArgumentException)` catches the whole family, and each member carries a `ParamName` property naming the offending parameter. | What is wrong with the argument | Type to throw | Example in the quote library | |---|---|---| | It is `null` | `ArgumentNullException` | `Quote(null, 2.5m)` | | It is outside the allowed range | `ArgumentOutOfRangeException` | a weight of `-1` kilogram | | Anything else about its value | `ArgumentException` | an address string that is empty | - **Prefer the most derived type.** `ArgumentNullException` tells the caller more than a bare `ArgumentException`. - **Set `ParamName`.** The constructors take it, and the static guard helpers such as `ArgumentNullException.ThrowIfNull` and `ArgumentOutOfRangeException.ThrowIfNegativeOrZero` fill it in from the argument expression (how those helpers work is covered with throwing and catching). - In a property setter, the parameter name is `value`. - `FormatException` is the usual type for text that does not match an expected format, as `int.Parse("abc")` throws, but it derives from `SystemException`, **not** from `ArgumentException`, so a `catch (ArgumentException)` does not catch it. ## Wrong state and unsupported operations Some calls fail although every argument is valid: - **`InvalidOperationException`**: the object is in the wrong state for this call, for example `Quote` before `LoadRates`, or `MoveNext` on an enumerator whose collection changed. - **`ObjectDisposedException`**: the object has been disposed. It derives from `InvalidOperationException`, because "disposed" is one particular wrong state. - **`NotSupportedException`**: the type does not support the operation at all, such as writing to a stream opened only for reading. - **`OverflowException`**: a conversion would overflow, for example in an explicit conversion operator. The distinction a reviewer listens for: an `ArgumentException` says *you passed me something wrong*, an `InvalidOperationException` says *you called me at the wrong time*. ## Types you never throw yourself 1. **Too general:** `Exception`, `SystemException` and `ApplicationException`. Throwing them forces callers to catch everything to catch yours. The guidelines also say not to derive from `ApplicationException`. 2. **Reserved for the runtime:** `NullReferenceException`, `IndexOutOfRangeException` and `AccessViolationException`. When one of these escapes a public method it usually means a bug inside that method; check the arguments so the caller gets an `ArgumentNullException` or `ArgumentOutOfRangeException` instead. 3. **Thrown only by the runtime:** `StackOverflowException`, `OutOfMemoryException` and `ExecutionEngineException`. The guidelines add that `StackOverflowException` must not be caught either. Code analysis rule **CA2201** reports both of the first two groups. It is off by default; with it enabled, `throw new Exception("Zero.")` produces `Exception type System.Exception is not sufficiently specific`, and `throw new NullReferenceException()` produces `Exception type System.NullReferenceException is reserved by the runtime`. ## A quick decision order When a method cannot do its job, walk these questions in order: 1. Is one of the **arguments** wrong? Throw from the `ArgumentException` family, most derived type first. 2. Is the **object** in the wrong state for this call? Throw `InvalidOperationException` (or `ObjectDisposedException`). 3. Does the type **never** support this operation? Throw `NotSupportedException`. 4. None of these, and callers would handle the failure separately? Only then consider a custom exception type, which has its own design rules. ## Putting it together ```csharp public decimal Quote(string address, decimal weightKg) { ArgumentNullException.ThrowIfNull(address); // ArgumentNullException, ParamName "address" ArgumentOutOfRangeException.ThrowIfNegativeOrZero(weightKg); // ArgumentOutOfRangeException if (!_ratesLoaded) throw new InvalidOperationException("Rates must be loaded before quoting."); return weightKg * 4.2m; } ``` Each failure now names its cause: the first two are bugs in the caller's code and are fixed by changing that code; the third is a sequencing mistake the caller can avoid by calling `LoadRates` first. None of them is something the caller should catch and carry on from in normal operation, and none of them needs a custom exception type, because a built-in type already says exactly what went wrong.

  • Why should a public method not let a NullReferenceException escape when a caller passes null?
    `NullReferenceException` is thrown by the runtime when code dereferences `null`, so callers read it as a bug inside your method and cannot see which argument was at fault. Checking the argument first and throwing `ArgumentNullException` with `ParamName` set tells the caller the mistake is theirs and names the parameter. CA2201 also lists `NullReferenceException` as reserved by the runtime.
  • Does catch (ArgumentException) also catch a FormatException from int.Parse?
    No. `FormatException` derives from `SystemException`, not from `ArgumentException`, so it passes straight by that clause. Only `ArgumentNullException`, `ArgumentOutOfRangeException` and other types derived from `ArgumentException` are caught. For expected bad text the better fix is `int.TryParse`, which returns `false` instead of throwing.

  • Throws new Exception("Invalid weight") for a bad argument
  • Uses ArgumentException for a call made before the object was initialised
  • Lets a NullReferenceException escape instead of checking the argument
  • Believes catch (ArgumentException) also catches FormatException
  • Throws ApplicationException because the error comes from application code
open as a page

In C#, what does a using statement do with the object it declares, and is Dispose still called when the block throws?

level: juniorimportance: must knowfreq 80%

basics

~20 s

A using statement calls Dispose on its resource when control leaves the block, however it leaves: normal completion, return, break or an exception. The compiler lowers it to try/finally, with a null check for reference types.

open as a page

In C#, what is the difference between `throw;` and `throw ex;` inside a catch block, and which one should you use to rethrow?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Both rethrow the same exception object, but throw ex; restarts its stack trace at the rethrow line and hides where the failure really happened, while a bare throw; keeps the original trace. Use throw; to rethrow from a catch block.

open as a page

In .NET, when should a throwing method such as Postcode.Parse get a TryParse companion, and what must that Try method still throw?

level: middleimportance: must knowfreq 55%

basics

~20 s

Add a TryX companion when callers routinely hit one expected failure, such as malformed input in an import: it returns false and leaves the out value at default instead of throwing. It still throws for any failure outside that defined case.

open as a page

How should a sealed C# class that creates and keeps its own FileStream and database connection implement IDisposable?

level: middleimportance: must knowfreq 60%

basics

~20 s

The class implements IDisposable, and its Dispose disposes the fields it created, returns early on a second call, and makes later member calls throw ObjectDisposedException. Being sealed with only managed fields, it needs no finalizer and no Dispose(bool).

open as a page

In C# 8 and later, when does a using declaration such as using var connection = Open(); dispose, and in what order do several dispose?

level: middleimportance: must knowfreq 65%

basics

~20 s

A using declaration disposes its variable when the enclosing block ends, not at the next line. Several declarations in one block dispose in reverse order of declaration, because the compiler nests one try/finally per declaration.

open as a page

In C#, why won't a `catch (Exception)` placed before `catch (FileNotFoundException)` compile, and how does the runtime pick which catch block runs?

level: middleimportance: must knowfreq 62%

basics

~20 s

The runtime tests catch clauses top to bottom and runs only the first whose type matches and whose filter, if any, is true. A general clause first would make the specific one unreachable, so the compiler rejects it with CS0160.

open as a page

In C#, when should a class implement IAsyncDisposable, and how does calling code make sure its DisposeAsync runs?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Implement IAsyncDisposable when cleanup must await I/O, such as flushing buffered messages over a network. DisposeAsync returns a ValueTask, and callers use await using so the compiler awaits it when the scope ends, even after an exception.

open as a page

In C#, what does the compiler generate for await using, and why does a plain using on an IAsyncDisposable-only type fail with CS8418?

level: middleimportance: should knowfreq 40%

basics

~20 s

await using compiles to try/finally that, if the resource is not null, awaits DisposeAsync in the finally; declarations dispose in reverse order. A plain using only accepts IDisposable, so an IAsyncDisposable-only type gets CS8418, suggesting await using.

open as a page

In C#, when does a library earn its own exception type such as CarrierUnavailableException, and how should that class be declared?

level: middleimportance: should knowfreq 45%

basics

~20 s

A custom exception earns its place when callers must catch that failure separately or read data no built-in type carries. Derive it from Exception, end the name in Exception, make it public, and give it the three standard constructors.

open as a page

In C#, how does a `catch (TimeoutException ex) when (...)` filter differ from catching, testing a condition and rethrowing with `throw;`?

level: middleimportance: should knowfreq 42%

basics

~20 s

A when filter runs before the stack unwinds; if it returns false, the exception keeps propagating untouched, as if that catch clause were not there. Catching and rethrowing unwinds first, running inner finally blocks, and then throws again from the catch block.

open as a page

In C#, what do `ArgumentNullException.ThrowIfNull` and the other guard helpers throw, and where does the parameter name in the exception come from?

level: middleimportance: should knowfreq 45%

basics

~20 s

ThrowIfNull throws ArgumentNullException when its argument is null; the string helpers add ArgumentException for empty or whitespace, and the range helpers throw ArgumentOutOfRangeException. A [CallerArgumentExpression] parameter makes the compiler pass the argument's source text as ParamName.

open as a page

How should an unsealed C# class implement both IDisposable and IAsyncDisposable so either disposal path releases everything exactly once?

level: seniorimportance: should knowfreq 32%

basics

~10 s

Add a protected virtual ValueTask DisposeAsyncCore beside Dispose(bool). DisposeAsync awaits DisposeAsyncCore, then calls Dispose(false) and GC.SuppressFinalize; both paths do the same cleanup, check whether it already ran, and can safely run twice.

open as a page

A C# quote gateway catches HttpRequestException and throws new CarrierUnavailableException(ex.Message); what do callers lose, and how should the wrap be written?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Passing only ex.Message throws away the original exception: its type, stack trace, properties and its own inner chain. Pass it as innerException so InnerException, GetBaseException and ToString keep the cause, and wrap only at the layer boundary.

open as a page

A C# report generator wraps a caller's Stream in a StreamWriter inside using, and the caller's next Write throws ObjectDisposedException; why, and what is the fix?

level: seniorimportance: should knowfreq 40%

basics

~20 s

By default a StreamWriter owns the stream it wraps, so disposing the writer also disposes the caller's stream. Construct it as new StreamWriter(output, leaveOpen: true): disposing it then flushes the writer but leaves the stream open for its owner.

open as a page

In C#, when does a disposable type need the Dispose(bool) pattern or a finalizer, and why does SafeHandle usually make the finalizer unnecessary?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Dispose(bool) is the hook an unsealed disposable class offers its subclasses. A finalizer is needed only by a type directly holding a raw unmanaged handle, and wrapping that handle in a SafeHandle subclass moves the finalizer into SafeHandle.

open as a page

In C#, what does a `finally` block guarantee, and when does it not run or end up hiding the original exception?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A finally block runs whenever control leaves its try block: normal exit, return, break, continue, goto, or an exception that something catches. Environment.FailFast, Environment.Exit, a stack overflow or a killed process skip it, and an exception thrown inside finally replaces the original.

open as a page

You lead a C# shipping-quote library used by three services; what convention would you set for throwing, Try methods, result objects and catch (Exception) handlers?

level: principalimportance: should knowfreq 35%

basics

~20 s

Throw for caller bugs and for failures the caller cannot prevent, return a Try method or a result object for outcomes callers branch on, and allow catch (Exception) only at each service's top-level boundary, which logs and decides. Enforce it with analyzers.

open as a page

As a lead, what ownership rule would you set for disposables a C# type creates or is given, and how should its API say who disposes?

level: principalimportance: should knowfreq 30%

basics

~20 s

A sound rule: whoever creates a disposable disposes it; a type never disposes what it is handed unless a flag like leaveOpen says so; factory methods transfer ownership to the caller. Enable CA2000 and CA2213, which are off by default.

open as a page

In C# library code, what does `await using var p = new Publisher().ConfigureAwait(false);` declare, and how should it be written instead?

level: middleimportance: nice to knowfreq 22%

basics

~10 s

It declares p as a ConfiguredAsyncDisposable, not a Publisher, so p.Publish fails with CS1061. Store the publisher in its own variable, then write await using (publisher.ConfigureAwait(false)); that configures only the final DisposeAsync await.

open as a page

In a C# payment-batch processor, a worker thread catches an item's exception and the coordinating thread must rethrow it; how does `ExceptionDispatchInfo` preserve the original stack trace?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

ExceptionDispatchInfo.Capture(ex) in the worker's catch block saves the exception together with its stack trace; calling Throw() on the coordinating thread rethrows the same object with that trace restored and the new frames appended after a marker line.

open as a page