Sundstrom.CheckedExceptions 1.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Sundstrom.CheckedExceptions --version 1.0.1                
NuGet\Install-Package Sundstrom.CheckedExceptions -Version 1.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sundstrom.CheckedExceptions" Version="1.0.1">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Sundstrom.CheckedExceptions --version 1.0.1                
#r "nuget: Sundstrom.CheckedExceptions, 1.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Sundstrom.CheckedExceptions as a Cake Addin
#addin nuget:?package=Sundstrom.CheckedExceptions&version=1.0.1

// Install Sundstrom.CheckedExceptions as a Cake Tool
#tool nuget:?package=Sundstrom.CheckedExceptions&version=1.0.1                

Checked Exceptions for C#

Enforce explicit exception handling in C#/.NET by ensuring all exceptions are either handled or declared.

This analyzer works with existing class libraries (including .NET class libraries) that have exceptions declared in XML documentation.

RepositoryNuGet Package


Table of Contents

  1. Features
  2. Installation
  3. Usage
  4. XML Documentation Support
  5. Examples
  6. Contributing
  7. License

Features

  • Enforce Explicit Exception Handling: Ensure all exceptions are either caught or explicitly declared using attributes.
  • Seamless Integration: Works with existing .NET class libraries that include exceptions in their XML documentation.
  • Custom Diagnostics: Provides clear diagnostics for unhandled or undeclared exceptions.
  • Support for XML Documentation: Leverages XML docs to identify exceptions from unannotated libraries.

Installation

You can install the package via the NuGet Gallery:

Install-Package Sundstrom.CheckedExceptions

Or via the .NET CLI:

dotnet add package Sundstrom.CheckedExceptionsAnalyzer

Usage

Defining ThrowsAttribute

To utilize CheckedExceptionsAnalyzer, you need to define the ThrowsAttribute in your project. Here's a simple implementation:

using System;

namespace CheckedExceptions
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Delegate, AllowMultiple = true)]
    public class ThrowsAttribute : Attribute
    {
        public Type ExceptionType { get; }

        public ThrowsAttribute(Type exceptionType)
        {
            if (!typeof(Exception).IsAssignableFrom(exceptionType))
                throw new ArgumentException("ExceptionType must be an Exception type.");

            ExceptionType = exceptionType;
        }
    }
}

Notes:

  • Namespace Choice: It's advisable to place ThrowsAttribute in a custom namespace (e.g., CheckedExceptions) rather than the System namespace to avoid potential conflicts with existing .NET types.

Annotating Methods

Annotate methods, constructors, or delegates that throw exceptions to declare the exceptions they can propagate.

using CheckedExceptions;

public class Sample
{
    [Throws(typeof(InvalidOperationException))]
    public void PerformOperation()
    {
        // Some operation that might throw InvalidOperationException
        throw new InvalidOperationException("An error occurred during the operation.");
    }
}

Handling Exceptions

Ensure that any method invoking annotated methods either handles the declared exceptions or further declares them.

using System;
using CheckedExceptions;

public class Sample
{
    public void Execute()
    {
        try
        {
            PerformOperation();
        }
        catch (InvalidOperationException ex)
        {
            // Handle invalid operations
        }
    }

    [Throws(typeof(InvalidOperationException))]
    public void PerformOperation()
    {
        // Some operation that might throw InvalidOperationException
        throw new InvalidOperationException("An error occurred during the operation.");
    }
}

Diagnostics

THROW001 (Unhandled Exception): In the Execute method, if PerformOperation throws an InvalidOperationException that is neither caught nor declared using ThrowsAttribute, the analyzer will report this diagnostic.

Example Diagnostic Message:

THROW001: Exception `InvalidOperationException` is thrown by `PerformOperation` but neither caught nor declared via `ThrowsAttribute`.

After properly handling the exception, no diagnostics are expected.

XML Documentation Support

CheckedExceptionsAnalyzer leverages XML documentation to identify exceptions from methods that do not have ThrowsAttribute annotations. This is particularly useful for:

  • Unannotated Libraries: Works with libraries that lack explicit exception annotations by using their XML documentation.
  • .NET Class Libraries: Extends support to the .NET framework by reading exceptions documented in XML.

If a library has both XML docs with exceptions and ThrowsAttribute annotations, the analyzer combines exceptions from both sources.

Example:

using System;
using System.IO;

public class FrameworkSample
{
    public void WriteToConsole()
    {
        // THROW001: Exception `IOException` is thrown by `Console.WriteLine` but neither caught nor declared via `ThrowsAttribute`.
        Console.WriteLine("Hello, World!");
    }
}

// Note: The Console class below is a simplified mock for demonstration purposes.
/// <summary>
/// Writes the specified value, followed by the current line terminator, to the standard output stream.
/// </summary>
/// <param name="value">
/// The value to write to the output. Can be of various types (e.g., string, object, etc.).
/// </param>
/// <remarks>
/// This method writes a line of text to the console. It automatically appends a newline at the end of the output.
/// </remarks>
/// <exception cref="System.IO.IOException">
/// An I/O error occurred.
/// </exception>
public class Console
{
    public void WriteLine(string value)
    {
        // Implemented in .NET
    }
}

In the above example, the analyzer identifies that Console.WriteLine can throw an IOException based on the XML documentation, even though ThrowsAttribute is not used.

Examples

Basic Usage

Annotating a Method:

using CheckedExceptions;

public class Calculator
{
    [Throws(typeof(DivideByZeroException))]
    public int Divide(int numerator, int denominator)
    {
        if (denominator == 0)
            throw new DivideByZeroException("Denominator cannot be zero.");

        return numerator / denominator;
    }
}

Handling Exceptions Example

Handling Declared Exceptions:

using System;
using CheckedExceptions;

public class CalculatorClient
{
    private Calculator _calculator = new Calculator();

    public void PerformDivision()
    {
        try
        {
            int result = _calculator.Divide(10, 0);
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Cannot divide by zero.");
        }
    }
}

In this example, the Divide method declares that it can throw a DivideByZeroException using ThrowsAttribute. The PerformDivision method handles this exception, thus complying with the analyzer's requirements.

Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/YourFeature).
  3. Commit your changes (git commit -m 'Add some feature').
  4. Push to the branch (git push origin feature/YourFeature).
  5. Open a pull request.

Please ensure your code adheres to the project's coding standards and includes appropriate tests.

License

This project is licensed under the MIT License.

There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Sundstrom.CheckedExceptions:

Repository Stars
marinasundstrom/YourBrand
Prototype enterprise system for e-commerce and consulting services
Version Downloads Last updated
1.2.3 128 11/30/2024
1.2.2 88 11/29/2024
1.2.1 92 11/28/2024
1.2.0 95 11/27/2024
1.1.9 97 11/26/2024
1.1.8 92 11/26/2024
1.1.7 94 11/26/2024
1.1.6 93 11/25/2024
1.1.5 91 11/25/2024
1.1.4 97 11/25/2024
1.1.3 107 11/24/2024
1.1.2 86 11/24/2024
1.1.1 88 11/24/2024
1.1.0 95 11/23/2024
1.0.9 101 11/22/2024
1.0.8 99 11/22/2024
1.0.7 96 11/21/2024
1.0.6 98 11/21/2024
1.0.5 94 11/20/2024
1.0.4 95 11/19/2024
1.0.3 94 11/19/2024
1.0.2 104 11/19/2024
1.0.1 103 11/19/2024
1.0.0 99 11/19/2024

Initial release