Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 278
Evan Avatar asked Aug 12 '10 20:08

Evan


People also ask

What exceptions can be thrown?

Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.

What kind of exception should I throw Java?

Only checked exceptions are required to be thrown using the throws keyword. Unchecked exceptions don't need to be thrown or handled explicitly in code.


1 Answers

  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
}
like image 175
PostMan Avatar answered Sep 24 '22 23:09

PostMan