我正在尝试编写一个函数,其中只有两个方法调用(方法为unit - > unit)应该处理某个异常。行为应该是:
- 如果引发异常,则整个功能结束
- 否则该函数继续(在异常处理程序之外)
起初我以为我可以使用包含在try / with块和continuation中的语句的函数,但当然可以从块中调用continuation ...我可以将语句包装在函数中并使用返回值表示成功/失败,但与下面的C#代码相比,这看起来很笨重,这就是我在F#中实现的目标。
SomeType MyMethod(string x)
{
...
try
{
foo();
bar();
}
catch(SomeException)
{
return null;
}
...
return ...;
}
答案 0 :(得分:4)
这样的东西?
// f <- foo(); bar(); etc...
// k <- unprotected continuation
let runProtected f k =
if try f(); true with _ -> false
then k()
else null
// sample from the question
let runProtected () =
if try
foo(); bar();
true
with _ ->
false
then unprotected()
else null
答案 1 :(得分:2)
我认为最好的惯用代码是使用选项类型:
member t.MyMethod(x : string) : SomeType =
let result =
try
foo()
bar()
Some(...)
with :? SomeException ->
None
match(result)
| Some(...) -> // do other work and return something
| None -> // return something
答案 2 :(得分:0)
怎么样:
let success =
try
foo ()
bar ()
true
with :? SomeException ->
false
if success then
...
else
()
答案 3 :(得分:0)
嗯......你可以做...
type Test() =
member this.MyMethod (x:string) =
if try
foo()
bar()
true
with _ -> false
then
// do more work
"blah"
else
null
或者,翻转真/假......
type Test() =
member this.MyMethod (x:string) =
if try
foo();
bar();
false
with _ -> true
then
// bail early
null
else
// do more work
"blah"
强烈建议从返回null切换到返回选项类型(Some(x)/ None)。让编译器捕获未处理null的位置,而不是用户; - )