C#:
void testFail()
{
try
{
Console.WriteLine("Ready for failing...");
throw new Exception("Fails");
}
catch (ArgumentException)
{
}
catch
{
}
}
F#相當於:
let testFail() =
try
printfn "Ready for failing..."
failwith "Fails"
with
| :? System.ArgumentException ->()
| _ ->()
C#:
void testFail()
{
try
{
Console.WriteLine("Ready for failing...");
throw new Exception("Fails");
}
catch (ArgumentException ex)
{
}
catch (Exception ex)
{
}
}
F#當量:
let testFail() =
try
printfn "Ready for failing..."
failwith "Fails"
with
| :? System.ArgumentException as ex ->()
| ex ->()
C#:
void testFail()
{
try
{
Console.WriteLine("Ready for failing...");
throw new Exception("Fails");
}
catch
{
}
}
F#當量:
let testFail() =
try
printfn "Ready for failing..."
failwith "Fails"
with
| _ ->()
正如Joel指出的那樣,您不希望在C#中使用catch (Exception)
,這與您在F#中不使用| :? System.Exception ->
的原因相同。
您的C#示例會爲使用ReSharper或FxCop的任何人導致警告。 [爲什麼?](http://blogs.msdn.com/b/codeanalysis/archive/2006/06/14/631923.aspx) –
@Joel Mueller,謝謝你的文章。我也不喜歡捕捉到一般的異常,但有時意外的異常可能會讓用戶感到困惑。 – LLS