Reputation: 4611
hi can any one tell me how to write user defined exceptions in C#?As we have in Java can we write in C#?
Upvotes: 5
Views: 10532
Reputation: 20571
It is practically the same as it is in Java - you extend the Exception
class.
In the most basic form.
public class CustomException : System.Exception
{
public CustomException()
{
}
public CustomException(string message)
: base(message)
{
}
public CustomException(string message, System.Exception innerException)
: base(message, innerException)
{
}
}
To this, then add the data that you want to capture using either fields or properties.
Out of interest, before answering this question, I checked the Microsoft Design Guildlines on Custom Exceptions. Designing Custom Exceptions (MSDN)
ArgumentException
. HOWEVER Do not derive from ApplicationException
. It is not harmful, it is no point in doing so. MSDN Blog Post on ApplicationException.ISerializable
interface. Apparently an exception must be serializable to work correctly across application domain and remoting boundaries.I highly recommend reading the Design Guidelines on MSDN.
Upvotes: 11
Reputation: 126992
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) { }
}
Upvotes: 16