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?
answer
- the argument family first
- most derived type that fits
- object state is not an argument
- ParamName names the culprit
- runtime-reserved types stay reserved
basics
~10 sThrow 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 sBad 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 linesvar 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
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.
Explain the inheritance: the argument types share ArgumentException and ParamName, ObjectDisposedException derives from InvalidOperationException, and FormatException is not an argument exception. Mention CA2201.
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.
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