Can anyone shed some light on the pros and cons of throwing custom exceptions (which inherit from System.Exception), or the proper way to use them? I'm already aware of the when/when not to throw exception, but I am looking for guidance on how to create my own custom exceptions.
The throw keyword is useful for throwing exceptions based on certain conditions e.g. if a user enters incorrect data. It is also useful for throwing custom exceptions specific to a program or application. Unchecked exceptions can be propagated in the call stack using the throw keyword in a method.
In C# there are three keywords Try, Catch, and Finally for handling exceptions. In try block statements it might throw an exception whereas catch handles that caused by try block if one exists. The finally block is used for doing any clean up process. The statement in finally block always executes.
C# allows us to create user-defined or custom exception. It is used to make the meaningful exception. To do this, we need to inherit Exception class.
These are all great posts. So far I agree most with Brian Rasmussen -- create custom exceptions when you want to handle different types of specific exceptions.
Perhaps an example will help. This is a contrived example, and may or may not be useful in everyday code. Suppose you have a class responsible for authenticating a user. This class, in addition to authenticating a user, has a lock-out mechanism to lock out a user after several failed attempts. In such a case, you might design as part of the class two custom exceptions: AuthenticationFailedException
and UserLockedOutException
. Your AuthenticateUser
method would then simply return without throwing if the user was successfully authenticated, throw AuthenticationFailedException
if the user failed authentication, or throw UserLockedOutException
if the user was locked out.
For example:
try
{
myAuthProvider.AuthenticateUser(username, password);
ShowAuthSuccessScreen();
}
catch(AuthenticationFailedException e)
{
LogError(e);
ShowAuthFailedScreen();
}
catch(UserLockedOutException e)
{
LogError(e);
ShowUserLockedOutScreen();
}
catch(Exception e)
{
LogError(e);
ShowGeneralErrorScreen();
}
Again, a contrived example. But hopefully it shows how and why you would want to create custom exceptions. In this case, the user of the AuthProvider
class is handling each custom exception in a different way. If the AuthenticateUser
method had simply thrown Exception
, there would be no way to differentiate between the different reasons why the exception was thrown.
There's actually a great series of MSDN articles on this topic:
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