.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh
Melody Anderson
Eminent IT

Home >> Code Snippets >> Bugs & Resolutions >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

custom exception classes in C#

Posted By:Ramesh P       Posted Date: October 31, 2010    Points: 15    Category: Bugs & Resolutions    URL: http://www.dotnetspark.com  

It helps to learn about custom exception classes

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.

Custom Exceptions

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
userObj )


          if ( some error condition )


                       throw new



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.


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend