How to catch any exception (System.Exception) without a warning in F#?
I tried to catch an Exception but the compiler gives warning: This type test or downcast will always hold
let testFail () =
try
printfn "Ready for failing..."
failwith "Fails"
with
| :? System.ArgumentException -> ()
| :? System.Exception -> ()
The question is: how to I do it with开发者_Python百科out the warning? (I believe there must be a way to do this, otherwise there should be no warning)
Like C#
try
{
Console.WriteLine("Ready for failing...");
throw new Exception("Fails");
}
catch (Exception)
{
}
C#:
void testFail()
{
try
{
Console.WriteLine("Ready for failing...");
throw new Exception("Fails");
}
catch (ArgumentException)
{
}
catch
{
}
}
F# equivalent:
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# equivalent:
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# equivalent:
let testFail () =
try
printfn "Ready for failing..."
failwith "Fails"
with
| _ -> ()
As Joel noted, you would not want to use catch (Exception)
in C# for the same reason you don't use | :? System.Exception ->
in F#.
try
.. code ..
with
| _ as e ->
精彩评论