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!
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.
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.
First, define MyAppCustomException
as an abstract base class.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With