Custom exceptions

All exceptions are derived from the System.Exception class in .NET Framework. So, in a scenario where these predefined exceptions don't suit our requirements, the framework allows us to create our own exceptions by deriving our exception class from the Exception class.

In the following example, we are creating a custom exception and inheriting from the Exception class. We can use different constructors for this:

public class MyCustomException : Exception
{
public MyCustomException():base("This is my custom exception")
{

}

public MyCustomException(string message)
: base($"This is from the method : {message}")
{

}

public MyCustomException(string message, Exception innerException)
: base($"Message: {message}, InnerException: {innerException}")
{
}
}

When you create your own exception class, derive from the System.Exception class, and implement the base class, you get four constructors; implementing the three mentioned is the best practice. In the first instance, the base class message property is initialized by default and a message is displayed. However, in the second and third scenarios, the method that's throwing this custom exception needs to pass these values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.181.47