gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:12:45 25 4
gpt4 key购买 nike

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

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

最佳答案

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
| _ -> ()

正如乔尔所指出的,你不会想使用 catch (Exception)在 C# 中,出于同样的原因,您不使用 | :? System.Exception ->在 F# 中。

关于exception-handling - 如何在 F# 中没有警告的情况下捕获任何异常 (System.Exception)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6616646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com