Unlike some other languages (like Java, which has "checked exceptions" where a method signature explicitly declares exceptions it might throw), C# does not have checked exceptions. A C# method's signature does not explicitly list the exceptions it might throw.
Therefore, in C#, functions primarily indicate potential exceptions through documentation and coding patterns.
Here are the main ways:
-
Documentation (XML Comments): This is the most common and recommended way. Developers use XML documentation comments, specifically the <exception> tag, to describe the conditions under which a method might throw a particular exception.
- How it works: When you write XML comments on a public or protected method, IDEs like Visual Studio or VS Code display this information in IntelliSense/tooltips when someone tries to use your method. Documentation generators can also create API documentation from these comments.
- Example:
/// <summary>
/// Divides two numbers.
/// </summary>
/// <param name="numerator">The number to divide.</param>
/// <param name="denominator">The number to divide by.</param>
/// <returns>The result of the division.</returns>
/// <exception cref="System.DivideByZeroException">Thrown when the denominator is zero.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown if numerator is extremely large.</exception>
public double Divide(double numerator, double denominator)
{
if (denominator == 0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}
// ... other logic ...
return numerator / denominator;
}
When someone types myObject.Divide(, the tooltip will show the summary, parameters, return value, and importantly, the <exception> entries indicating possible errors.
-
Method Naming and Design Patterns: Certain naming conventions or design patterns signal that a method might fail in a predictable way, often indicating that an exception might be involved in an alternative version of the method.
Try... Methods: Methods following the Try... pattern (like int.TryParse, Dictionary<TKey, TValue>.TryGetValue) return a bool indicating success or failure, and use out parameters for the result. These methods are specifically designed not to throw an exception when a common, expected failure occurs (like parsing an invalid string or looking up a non-existent key). The non-Try equivalent (e.g., int.Parse, Dictionary<TKey, TValue>[key]) will throw an exception on failure. This pattern implicitly signals the potential for an exception if you don't use the Try version.
// This *will* throw if the string is not a valid integer
// int value = int.Parse("abc");
// This *will not* throw if the string is not a valid integer,
// but returns false. It signals potential failure.
if (int.TryParse("abc", out int value))
{
// success
}
else
{
// failure, but no exception
}
- Naming indicating failure: While less formal, names like
GetDataOrThrowIfFailed, ThrowIfNull also explicitly communicate the intent to throw under certain conditions.
-
Implicit Knowledge (Common Exceptions): Developers are expected to be aware of common exceptions that can occur in many operations:
NullReferenceException: Accessing a member on a null object.
ArgumentNullException, ArgumentOutOfRangeException: Invalid input parameters.
IOException, FileNotFoundException: File or network operations.
OutOfMemoryException: System resource issues.
InvalidOperationException: The operation is not valid for the current state of the object.
In summary, while C# lacks explicit exception declarations in the method signature, developers rely heavily on XML documentation (<exception>) and standard design patterns (Try... methods) to communicate potential exceptions to callers. The responsibility lies with the developer creating the function to document its behavior and with the caller to read the documentation and handle potential exceptions appropriately using try-catch blocks where necessary.