Is there a way to know what is passed to method when an exception is thrown.e.g; Convert.ToBoolean(string mystring)
when it 开发者_StackOverflowthrows FormatException?
Here I want to know what was mystring when exception was thrown?
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);
}
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.
You should just be using Boolean.TryParse
. Then you can say
bool value;
if(!Boolean.TryParse(myString, out value)) {
// it didn't parse
}
// it parsed
精彩评论