Lets Learn

Opinion Matters

Question # 4

Posted by Ankush on February 9, 2011


Using reflection, you invoke a method that generates an exception. You want to obtain the real exception object to work with it.

Any possible solution ( small code snippet will help :))?

Advertisements

3 Responses to “Question # 4”

  1. ajay said

    Here is how we can obtain the ‘real’ exception. Suppose i have following class:

    namespace TestClassLibrary1
    {
    public class Class1
    {
    public string helloWorld()
    {
    throw new NullReferenceException();
    return “hello world”;
    }
    }
    }

  2. ajay said

    Here is the code which calls the function and catches the exception:
    static void Main(string[] args)
    {
    Assembly asm = Assembly.LoadFrom(@”C:\Users\ajayban\Documents\Visual Studio 2008\Projects\TestClassLibrary1\TestClassLibrary1\bin\Debug\TestClassLibrary1.dll”);
    Type t1 = asm.GetType(“TestClassLibrary1.Class1”);
    Object type = asm.CreateInstance(“TestClassLibrary1.Class1”, true);
    try
    {
    string result = (string)t1.InvokeMember(“helloWorld”, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, type, null);
    }
    catch(Exception ex)
    {
    Console.WriteLine(ex.InnerException.Message);

    }

    Console.ReadKey();
    }

  3. thnx bro

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: