public static void Main()
new Temp().ConditionalThrow(t => true, typeof(MyException), "Alberto", "25");
Console.WriteLine(ex.Message);
new Temp().ConditionalThrow(t => true, typeof(MyException));
Console.WriteLine(ex.Message);
new Temp().ConditionalThrow(t => true, typeof(string));
catch (ArgumentException ex)
Console.WriteLine(ex.Message);
internal static TSource ConditionalThrow<TSource>(this TSource source, Func<TSource, bool> throwCondition, Type exceptionType, params object[] arguments)
if (!typeof(Exception).IsAssignableFrom(exceptionType))
throw new ArgumentException("exceptionType is not an Exception");
if (throwCondition(source))
throw Activator.CreateInstance(exceptionType, arguments) as Exception;
public string Name { get; set; }
public class MyException : Exception
public MyException(string name, string age)
: base($"Name: {name} and Age: {age}")