hi can any one tell me how to write user defined exceptions in C#?As we have in Java can we write in C#?
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.
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 .
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.
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) { }
}
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