Search code examples
c#custom-exceptions

What type of exception to throw in this case?


I'm writing a c# application which uses automation to control another program. Naturally that program must be running for my program to work. When my program looks for the application and can't find it I'd like to throw an exception (for now later of course I could try opening the application, or telling the user to open it, or ...).

Should I implement a custom exception - or use the existing NotSupportedException (or one of the other .NET exceptions). If a custom exception, what would you suggest? I was thinking of implementing a custom exception I'd call it MyAppNameException and then just use the message to declare what the problem was?

Are there any general rules to throwing exceptions in a way that makes your program more readable and user friendly, or am I just giving this too much thought :)?

Thanks!


Solution

    1. First, define MyAppCustomException as an abstract base class.

    2. Then inherit from it with AppNotFoundCustomException.

    This way you can catch all exceptions from your app, or just specific ones.

    Here's some example code that illustrates the concept:

    public abstract class MyAppCustomException : System.Exception
    {
        internal MyAppCustomException(string message)
            : base(message)
        {
        }
    
        internal MyAppCustomException(string message, System.Exception innerException)
            : base(message,innerException)
        {            
        }
    }
    
    public class AppNotFoundCustomException : MyAppCustomException
    {
        public AppNotFoundCustomException(): base("Could not find app")
        {
        }
    }
    

    And here's a client try/catch example:

    try 
    {
       // Do Stuff
    }
    catch(AppNotFoundCustomException)
    {
       // We know how to handle this
    }
    catch(MyAppCustomException) // base class
    {
       // we don't know how to handle this, but we know it's a problem with our app
    }