Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

5.6. Handling Exceptions Thrown from Methods Invoked via Reflection

Problem

Using reflection, you invoke a method that generates an exception. You want to obtain the real exception object and its information in order to diagnose and fix the problem.

Solution

The real exception and its information can be obtained through the InnerException property of the TargetInvocationException exception that is thrown by MethodInfo.Invoke.

Discussion

The following example shows how an exception that occurs within a method invoked via reflection is handled. The Reflect class contains a ReflectionException method that invokes the static TestInvoke method using the reflection classes as shown here:

using System; using System.Reflection; public class Reflect { public void ReflectionException( ) { Type reflectedClass = typeof(Reflect); try { MethodInfo methodToInvoke = reflectedClass.GetMethod("TestInvoke"); if (methodToInvoke != null) { object oInvoke = methodToInvoke.Invoke(null, null); } } catch(Exception e) { Console.WriteLine("MESSAGE: " + e.Message); Console.WriteLine("SOURCE: " + e.Source); Console.WriteLine("TARGET: " + e.TargetSite); Console.WriteLine("STACK: " + e.StackTrace + "\r\n"); if(e.InnerException != null) { Console.WriteLine( ); Console.WriteLine("\t**** INNEREXCEPTION START ****"); Console.WriteLine("\tTYPE THAT THREW EXCEPTION: " + reflectedClass.ToString( )); Console.WriteLine("\tINNEREXCEPTION MESSAGE: " + e.InnerException.Message); Console.WriteLine("\tINNEREXCEPTION SOURCE: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata