Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I include an object carrying additional information in the exception?

Tags:

c#

exception

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.

like image 705
Álvaro García Avatar asked Dec 28 '12 17:12

Álvaro García


People also ask

Which of this exception comes under System exception?

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.

Can we throw custom exception in catch block?

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.

Which of the following are methods or properties of System exception?

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.

How do you handle exceptions in C#?

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.


1 Answers

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 */ }
like image 85
hometoast Avatar answered Oct 11 '22 12:10

hometoast