How to catch any exception (System.Exception) without a warning in F#?

大兔子大兔子 提交于 2019-12-06 17:55:40

问题


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)
{
}

回答1:


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#.




回答2:


try 
  .. code ..
with
  | _ as e -> 


来源:https://stackoverflow.com/questions/6616646/how-to-catch-any-exception-system-exception-without-a-warning-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!