org.sonar.plugins.csharp.S112.html Maven / Gradle / Ivy
This rule raises an issue when a general or reserved exception is thrown.
Why is this an issue?
Throwing general exceptions such as Exception
, SystemException
and ApplicationException
will have a negative
impact on any code trying to catch these exceptions.
From a consumer perspective, it is generally a best practice to only catch exceptions you intend to handle. Other exceptions should ideally be let
to propagate up the stack trace so that they can be dealt with appropriately. When a general exception is thrown, it forces consumers to catch
exceptions they do not intend to handle, which they then have to re-throw.
Besides, when working with a general type of exception, the only way to distinguish between multiple exceptions is to check their message, which is
error-prone and difficult to maintain. Legitimate exceptions may be unintentionally silenced and errors may be hidden.
For instance, if an exception such as StackOverflowException
is caught and not re-thrown, it may prevent the program from terminating
gracefully.
When throwing an exception, it is therefore recommended to throw the most specific exception possible so that it can be handled intentionally by
consumers.
Additionally, some reserved exceptions should not be thrown manually. Exceptions such as IndexOutOfRangeException
,
NullReferenceException
, OutOfMemoryException
or ExecutionEngineException
will be thrown automatically by the
runtime when the corresponding error occurs. Many of them indicate serious errors, which the application may not be able to recover from. It is
therefore recommended to avoid throwing them as well as using them as base classes.
How to fix it
To fix this issue, make sure to throw specific exceptions that are relevant to the context in which they arise. It is recommended to either:
- Throw a subtype of
Exception
when one matches. For instance ArgumentException
could be raised when an unexpected
argument is provided to a function.
- Define a custom exception type that derives from
Exception
or one of its subclasses.
Code examples
Noncompliant code example
public void DoSomething(object obj)
{
if (obj == null)
{
throw new NullReferenceException("obj"); // Noncompliant: This reserved exception should not be thrown manually
}
// ...
}
Compliant solution
public void DoSomething(object obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj"); // Compliant: this is a specific and non-reserved exception type
}
// ...
}
Resources
Standards