How to write custom exception classes in C#
The Microsoft .NET team has done a good job by providing us
a rich set of Exception classes. Most of the time, these exception classes are
sufficient enough to handle any common error situation. However, it may be
required that our application would need some additional exception classes,
that are not available in .NET Framework.
The .NET Framework exception handling mechanism allows us to create our own
custom exception classes and use it in our applications.
All exceptions in .NET are derived from the root exception class -
System.Exception. There are two other
exception classes immediately derived from the System.Exception :
All exceptions thrown by the .NET Framework is derived from the SystemException
class. If we raise any exception from our application, it should be derived
from the System.ApplicationException. This will differentiate our exceptions
from the system generated exceptions.
It is easy to create a custom exception class. Just create a new class and mark
it as derived from System.ApplicationException
public class UserNotExistsException : System.ApplicationException
Now we have derived a custom exception class and we can use it in ourr
application. See the sample code, showing how we
can throw ourr custom exception.
public void UpdateUser( User
if ( some error condition )
The 'throw' statement allows us to raise an exception programmatically. Here we
are creating a new object of type 'UserNotExistsException' and throwing it.
Another class or method which calls our method should handle this exception.
UpdateUser( userObj );
catch ( UserNotExistsException ex)
MessageBox.Show (ex.Message );
In this sample, we are calling the method UpdateUser(...), which might throw an
exception of type UserNotExistsException. If this exception is raised, it will
go to our catch block and we are showing a message to the user.