Der obige Block bezieht sich auf eine andere Frage + Antwort auf SO enthält keine korrekte Antwort, die hier gilt!Wird eine generische Ausnahme in einem Catch unterstützt?
Ich habe eine Methode für Unit-Tests verwendet. Der Zweck dieser Methode besteht darin, sicherzustellen, dass ein Codeabschnitt (auf den ein Delegat verweist) eine bestimmte Ausnahme auslöst. Wenn diese Ausnahme ausgelöst wird, ist der Komponententest erfolgreich. Wenn keine Ausnahme ausgelöst wird oder eine andere Typausnahme ausgelöst wird, schlägt der Komponententest fehl.
/// <summary>
/// Checks to make sure that the action throws a exception of type TException.
/// </summary>
/// <typeparam name="TException">The type of exception expected.</typeparam>
/// <param name="action">The code to execute which is expected to generate the exception.</param>
public static void Throws<TException>(Action action)
where TException : Exception
{
try
{
action();
}
catch (TException)
{
return;
}
catch (Exception ex)
{
Assert.Fail("Wrong exception was thrown. Exception of type " + ex.GetType() + " was thrown, exception of type " + typeof(TException) + " was expected.");
}
Assert.Fail("No exception was thrown. Exception of type " + typeof(TException) + " was expected.");
}
Das soll nächster Aufruf erfolgreich zu sein, aber es funktioniert nicht:
int result = 0;
Throws<DivideByZeroException>(() => result = result/result);
Wenn die erwartete Ausnahme des Typs TException
geworfen wird, es immer von dem zweiten Fang gefangen wird, nicht durch den ersten Fang. Warum ist das?
Natürlich kann ich ein Workarround mit einem Catch verwenden und testen, ob ex
vom Typ TException
ist. Ich möchte einfach wissen/verstehen, warum dieser Code kompiliert, aber einfach (nie?) Funktioniert.
EDIT
Auf Wunsch eine "Arbeits" Demo:
using System;
namespace GenericExceptionDemo
{
class Program
{
static void Main(string[] args)
{
int n = 0;
Catch<DivideByZeroException>(() => n = n/n);
}
static public void Catch<TException>(Action action)
where TException: Exception
{
try
{
action();
Console.WriteLine("No exception thrown. !!!Fail!!!");
}
catch (TException)
{
Console.WriteLine("Expected exception thrown. PASS!");
}
catch(Exception ex)
{
Console.WriteLine("An unexpected exception of type " + ex.GetType() + " thrown. !!!FAIL!!!");
}
}
}
}
Welches Einheitentestframework verwenden Sie? Die meisten haben bereits 'Assert.Throws' ... –
Ihr Code funktioniert für mich ... bitte zeigen Sie ein kurzes aber vollständiges Programm, das das Problem demonstriert. –
Warum soll angegeben werden, dass eine falsche Art von Ausnahme ausgelöst wird? Vielleicht wirft .NET Framework selbst eine System.Drawing.Exception, wenn Sie mit GUIs arbeiten? –