Reputation: 2228
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 without 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)
{
}
Upvotes: 17
Views: 6147
Reputation: 62975
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#.
Upvotes: 37