Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the parameter value of method on exception

Is there a way to know what is passed to method when an exception is thrown.e.g; Convert.ToBoolean(string mystring) when it throws FormatException? Here I want to know what was mystring when exception was thrown?

like image 553
Zain Ali Avatar asked Jul 22 '11 01:07

Zain Ali


2 Answers

You have to capture the general exception (or FormatException) and assign your values to Exception.Data member. Or re-throw a new exception with your values.

using Exception.Data

How to add your extra information

catch (Exception e)
            {
            e.Data.Add("ExtraInfo", "More information.");
            throw e;
            }

How to catch

 catch (Exception e)
            {
            if (e.Data != null)
                {
            foreach (DictionaryEntry de in e.Data)
                    Console.WriteLine("    The key is '{0}' and the value is: {1}", 
                                                    de.Key, de.Value);                  
                }
            }

// Or simply re throw a new exception with your string...

catch (Exception ex)
{     
     throw new Exception("My string was" + yourString);
}
like image 107
CharithJ Avatar answered Sep 23 '22 14:09

CharithJ


You can still get the value of the variables inside the catch block as long as its either the parameters or variables declared above the try block.
You have to either catch specific exceptions such as argumentnullexception/formatexception or wrap individual operations within the method in a try/catch block, to know the context where the exception was thrown.

void Method(int i, string j)
{
    bool p;

    try
    {

    }
    catch(FormatException e)
    {
      //value of i, j, p are available here.
    }
}

The ideal way is to check for possible situations where exceptions (such as formatexceptions) are thrown and prevent them. They are expensive and interrupts the process flow.

like image 31
coder net Avatar answered Sep 19 '22 14:09

coder net