Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write User Defined exceptions in C#?

Tags:

c#

exception

hi can any one tell me how to write user defined exceptions in C#?As we have in Java can we write in C#?

like image 624
Hemant Kumar Avatar asked Oct 04 '10 04:10

Hemant Kumar


People also ask

How do you declare a user defined exception?

In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword. For example, MyException in the below code extends the Exception class.

How user defined exceptions write syntax?

When creating your own exceptions, end the class name of the user-defined exception with the word "Exception", and implement the three common constructors, as shown in the following example. The example defines a new exception class named EmployeeListNotFoundException .

What are user defined exceptions explain with an example in C#?

An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Define your own exception. User-defined exception classes are derived from the Exception class.


1 Answers

You want to inherit from System.Exception and preferrably provide (at minimum) the same public constructors and pass the parameters on to the base constructors. Add the relevant properties and/or methods you deem appropriate for your particular need.

public class MyException : System.Exception
{
     public MyException() : base() { }
     public MyException(string message) : base(message) { }
     public MyException(string message, Exception innerException) : base(message, innerException) { }
} 
like image 63
Anthony Pegram Avatar answered Oct 20 '22 13:10

Anthony Pegram