如何在F#中没有警告的情况下捕获任何异常(System.Exception)?

时间:2011-07-07 20:20:33

标签: exception-handling f#

我试图捕获异常,但编译器发出警告:此类型测试或向下转换将始终保持

let testFail () =
    try
        printfn "Ready for failing..."
        failwith "Fails"
    with
    | :? System.ArgumentException -> ()
    | :? System.Exception -> ()

问题是:如何在没有警告的情况下这样做? (我相信必须有办法做到这一点,否则应该没有警告)

喜欢C#

try
{
    Console.WriteLine("Ready for failing...");
    throw new Exception("Fails");
}
catch (Exception)
{
}

2 个答案:

答案 0 :(得分:34)

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 ->的原因相同。

答案 1 :(得分:5)

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