c# - How to catch Exception thrown in a method invoked by using MethodInfo.Invoke? -
i have following codes:
using system; using system.reflection; namespace testinvoke { class program { static void main( string[] args ) { method1(); console.writeline(); method2(); } static void method1() { try { myclass m = new myclass(); m.mymethod( -3 ); } catch ( exception e ) { console.writeline( e.message ); } } static void method2() { try { string classname = "testinvoke.myclass"; string methodname = "mymethod"; assembly assembly = assembly.getentryassembly(); object myobject = assembly.createinstance( classname ); methodinfo methodinfo = myobject.gettype().getmethod( methodname ); methodinfo.invoke( myobject, new object[] { -3 } ); } catch ( exception e ) { console.writeline( e.message ); } } } public class myclass { public void mymethod( int x ) { if ( x < 0 ) throw new applicationexception( "invalid argument " + x ); // } } } method1 , method2 both execute myclass.mymethod, method1 outputs:
invalid argument -3 while method2 outputs:
exception has been thrown target of invocation. could modify method2 catch exception in method1?
take @ innerexception. in .net reflection wrap exception - can useful knowing how exception called. see inner exception property has exception looking for. 
so have same exception call console.writeline(e.innerexception.message) instead.
Comments
Post a Comment