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#中不使用的原因相同.
try
.. code ..
with
| _ as e ->
Run Code Online (Sandbox Code Playgroud)