Exception Must Be Thrown
ID |
csharp.exception_must_be_thrown |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
CSharp |
Tags |
exception-handling, reliability |
Description
Reports new SomeException(…) expressions that are constructed but never raised: the
allocation is a statement on its own (or evaluated and discarded) without a throw
keyword in front of it.
Rationale
Constructing an exception is the diagnostic side of the work — the run-time error is
only surfaced by the throw that follows. A bare new InvalidOperationException(…)
statement runs without effect: the program flow continues, the failure goes unreported,
and the caller sees normal completion. The pattern almost always comes from a missing
throw keyword introduced during a refactor.
public void Validate(string s)
{
if (string.IsNullOrEmpty(s))
new ArgumentException("bad input"); // FLAW — missing throw
if (s.Length > 100)
{
new InvalidOperationException("too long"); // FLAW
}
}
public void Ok(string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentException("bad input"); // OK
}
public Exception MakeError(string s) =>
new InvalidOperationException(s); // OK — returned to caller
Remediation
Add the missing throw keyword. If the construction is intentional (for example to
populate a logging record or test fixture), assign it to a variable so the intent is
explicit.