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

LLS*_*LLS 15 f# exception-handling

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

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

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

喜欢C#

try
{
    Console.WriteLine("Ready for failing...");
    throw new Exception("Fails");
}
catch (Exception)
{
}
Run Code Online (Sandbox Code Playgroud)

ild*_*arn 35

C#:

void testFail()
{
    try
    {
        Console.WriteLine("Ready for failing...");
        throw new Exception("Fails");
    }
    catch (ArgumentException)
    {
    }
    catch
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

F#等价物:

let testFail () =
    try
        printfn "Ready for failing..."
        failwith "Fails"
    with
    | :? System.ArgumentException -> ()
    | _ -> ()
Run Code Online (Sandbox Code Playgroud)

C#:

void testFail()
{
    try
    {
        Console.WriteLine("Ready for failing...");
        throw new Exception("Fails");
    }
    catch (ArgumentException ex)
    {
    }
    catch (Exception ex)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

F#等价物:

let testFail () =
    try
        printfn "Ready for failing..."
        failwith "Fails"
    with
    | :? System.ArgumentException as ex -> ()
    | ex -> ()
Run Code Online (Sandbox Code Playgroud)

C#:

void testFail()
{
    try
    {
        Console.WriteLine("Ready for failing...");
        throw new Exception("Fails");
    }
    catch
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

F#等价物:

let testFail () =
    try
        printfn "Ready for failing..."
        failwith "Fails"
    with
    | _ -> ()
Run Code Online (Sandbox Code Playgroud)

正如Joel所说,你不想catch (Exception)在C#中使用,原因与你| :? System.Exception ->在F#中不使用的原因相同.


lib*_*tor 5

try 
  .. code ..
with
  | _ as e -> 
Run Code Online (Sandbox Code Playgroud)

  • `_`确实是多余的,实际上这段代码破坏了`_`变量的用途`| _ as e -> (...)` 与 `| 没有什么不同 e -> (..) ` 在模式匹配语句中任何没有保护子句的 var 都是一个包罗万象的,命名变量 `_` 只是表明你不关心这个值。给 `_` 取别名首先会破坏 `_`。 (2认同)