6

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?

3 Answers 3

7

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Note: You can replace "throw e" with "throw" and it still will preserve the stacktrace while containing the new user data.
3

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.

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.