Advertisement
Guest User

Generic Exception Handling

a guest
Jan 27th, 2012
1,271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3.  
  4. namespace GenericConsoleApp
  5. {
  6.     public class GenericException : Exception
  7.     {
  8.         public GenericException(string message)
  9.             : base(message)
  10.         {
  11.         }
  12.     }
  13.  
  14.     public class GenericException<T> : GenericException
  15.     {
  16.         private T mValue;
  17.  
  18.         public GenericException(string message, T value)
  19.             : base(message)
  20.         {
  21.             mValue = value;
  22.         }
  23.  
  24.         public T Value
  25.         {
  26.             get { return mValue; }
  27.         }
  28.     }
  29.  
  30.     class Program
  31.     {
  32.         static void Main(string[] args)
  33.         {
  34.             HandleException<int>();
  35.             HandleException<object>();
  36.             HandleException<Exception>();
  37.             HandleException<Program>();
  38.  
  39.             Console.ReadKey();
  40.         }
  41.  
  42.         static void HandleException<T>()
  43.             where T : new()
  44.         {
  45.             try
  46.             {
  47.                 ThrowException<T>();
  48.             }
  49.             catch (GenericException ex)
  50.             {
  51.                 Type exceptionType = ex.GetType();
  52.  
  53.                 if (exceptionType.IsGenericType)
  54.                 {
  55.                     // Find the type of the generic parameter
  56.                     Type genericType = ex.GetType().GetGenericArguments().FirstOrDefault();
  57.  
  58.                     if (genericType != null)
  59.                     {
  60.                         Console.WriteLine("Caught exception of type '{0}'.", genericType.FullName);
  61.                     }
  62.                 }
  63.             }
  64.             catch (Exception)
  65.             {
  66.                 Console.WriteLine("Failed to handle specific exception.");
  67.             }
  68.         }
  69.  
  70.         static void ThrowException<T>()
  71.             where T : new()
  72.         {
  73.             throw new GenericException<T>(
  74.                 string.Format("Exception of type '{0}' has been thrown.", typeof(T).FullName),
  75.                 new T()
  76.             );
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement