Skip to content

Instantly share code, notes, and snippets.

@carloshm
Last active February 20, 2023 14:19
Show Gist options
  • Save carloshm/2e98ada4da163b2d089d19b4713054fd to your computer and use it in GitHub Desktop.
Save carloshm/2e98ada4da163b2d089d19b4713054fd to your computer and use it in GitHub Desktop.
Internal exception class and use it within a public class

In C# I can't throw an internal exception from the private method of a public class, even if I absolutely always catch it so it doesn't get exposed outside of the assembly... any workaround for this other than making the exception class public?

In C#, internal exceptions are designed to only be visible within the assembly where they are defined. However, since you cannot throw an internal exception from a private method of a public class, one workaround is to define a custom exception class that is visible within the assembly, but not outside of it.

Note: Check visibility at https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute?view=net-7.0

Here's an example of how you can define an internal exception class and use it within a public class:

// Define an internal exception class within the assembly
namespace MyAssembly.Internal
{
    internal class MyInternalException : Exception
    {
        // Constructor
        public MyInternalException(string message) : base(message)
        {
        }
    }
}

// Define a public class that uses the internal exception
namespace MyAssembly.Public
{
    public class MyClass
    {
        private void MyPrivateMethod()
        {
            try
            {
                // Do something that might throw an internal exception
            }
            catch (Exception ex)
            {
                // Catch the internal exception and re-throw it as a public exception
                throw new MyInternalException("An internal error occurred.", ex);
            }
        }
    }
}

In this example, the MyInternalException class is defined within the assembly using the internal access modifier. This makes the exception class visible only within the assembly, so it cannot be accessed from outside of it.

The MyClass public class uses the MyInternalException class within its private method by catching the internal exception and re-throwing it as a public exception. This way, the internal exception is caught and handled within the assembly, but the public exception can still be thrown and caught outside of the assembly.

By using this approach, you can keep your internal exception class internal, while still being able to use it within your public class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment