Exception Throwing Filter - CSharp Custom Type

CSharp examples for Custom Type:Exception

Description

Exception Throwing Filter

Demo Code

using System;//  w ww. jav  a 2s .  co  m
using System.Reflection;
class ExceptionThrowingFilter
{
   static void Main()
   {
      var instance = new ExceptionThrowingFilter();
      try
      {
         instance.MethodCaller();
      }
      catch (Exception e)
      {
         Console.WriteLine($"Caught: {e.Message}");
      }
      Console.WriteLine("Calling with reflection");
      try
      {
         typeof(ExceptionThrowingFilter).GetMethod(nameof(MethodCaller)).Invoke(instance, null);
      }
      catch (TargetInvocationException e)
      {
         Console.WriteLine($"Caught: {e.InnerException.Message}");
      }
      Console.WriteLine("Calling dynamically");
      try
      {
         dynamic d = instance;
         d.MethodCaller();
      }
      catch (Exception e)
      {
         Console.WriteLine($"Caught: {e.Message}");
      }
   }
   public void MethodCaller()
   {
      try
      {
         ThrowingMethod();
      }
      catch (Exception e) when (Log(e))
      {
       }
    }
    static bool Log(Exception e)
    {
       Console.WriteLine($"Filtered: {e.Message}");
       return false;
    }
    public static void ThrowingMethod()
    {
       try
       {
          throw new Exception("Short message");
       }
       catch (Exception e) when (e.Message[100] == 'x')
       {
       }
    }
}

Result


Related Tutorials