Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- namespace GenericConsoleApp
- {
- public class GenericException : Exception
- {
- public GenericException(string message)
- : base(message)
- {
- }
- }
- public class GenericException<T> : GenericException
- {
- private T mValue;
- public GenericException(string message, T value)
- : base(message)
- {
- mValue = value;
- }
- public T Value
- {
- get { return mValue; }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- HandleException<int>();
- HandleException<object>();
- HandleException<Exception>();
- HandleException<Program>();
- Console.ReadKey();
- }
- static void HandleException<T>()
- where T : new()
- {
- try
- {
- ThrowException<T>();
- }
- catch (GenericException ex)
- {
- Type exceptionType = ex.GetType();
- if (exceptionType.IsGenericType)
- {
- // Find the type of the generic parameter
- Type genericType = ex.GetType().GetGenericArguments().FirstOrDefault();
- if (genericType != null)
- {
- Console.WriteLine("Caught exception of type '{0}'.", genericType.FullName);
- }
- }
- }
- catch (Exception)
- {
- Console.WriteLine("Failed to handle specific exception.");
- }
- }
- static void ThrowException<T>()
- where T : new()
- {
- throw new GenericException<T>(
- string.Format("Exception of type '{0}' has been thrown.", typeof(T).FullName),
- new T()
- );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement