I would like to define a custom exception, and I would like to know if I can include a class instead of a string as the message. The reason is that I would like to send extra information in a structure that can be more flexible.
The SystemException is a predefined exception class in C#. It is used to handle system related exceptions. It works as base class for system exception namespace. It has various child classes like: ValidationException, ArgumentException, ArithmeticException, DataException, StackOverflowException etc.
But with custom exceptions, you can throw and catch them in your methods. Custom exceptions enable you to specify detailed error messages and have more custom error handling in your catch blocks.
Exception class properties The Exception class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.
Use a try block around the statements that might throw exceptions. Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.
Yes. Just create a class that inherits from Exception.
class YourException : Exception
{
public YourException(SpecialObject thethingYouWantIncluded)
{
ExtraObject = thethingYouWantIncluded;
}
public SpecialObject ExtraObject { get; private set; }
}
then
throw new YourException(new SpecialObject());
and
catch (YourException ex) { /* do something with ex.ExtraObject here */ }
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