Print this page
Tuesday, 25 December 2012 13:54

how to create Own Exception Classes in C#.net

Written by 
Rate this item
(0 votes)

for creating own exception class,you have to derive your class
from System.Exception class.also you have to implement all
constructors which base class implements.to create own
exception class follow the requirements/recommendations
below-

1.you have to provide a meaningful name to your class ending with
Exception.
2.if there is no scenario for programmers needing the class
then do not create a exception class
3.throw the exception most specifically
4.if you use innerExceptions then good.
5.throw ArgumentException or it's subclass when false arguments
have been passed.

following are the codes for creating a exception-TestException-

using System;
public class TestException : Exception
{
//Constructors. It is recommended to use all
public TestException() : base() { }
public TestException(string testMessage) : base(testMessage) { }
public TestException(string testMessage, Exception e) :
base(testMessage, e) { }
//create needed properties for extra error information.
private string strExtraInformation;
public string ExtraErrorInformation{
get{return strExtraInformation;}
set{strExtraInformation = value;}}

public class TestTestException{
public static void Main(){
try{TestException obj;
obj = new TestException("My Exception Occured");
obj.ExtraErrorInformation = "Extra Error Info";
throw obj;} catch (TestException e){
Console.Write(String.Concat(e.StackTrace, e.Message));
Console.Write(e.ExtraErrorInformation);}
Console.Read();}}
}

code summary::

in the above exception class i created is come from the base
System.Exception class.first all constructors called the
constructors of base class.I also created property-
ExtraErroInfo to store extra error info.

Read 2525 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.
7