我正在寻找一种模式来处理伪代码中的代码:
enum ForeseenError : Error {
case likelyProblem
case unlikelyProblem
}
func planA () throws {
print ("planA")
throw ForeseenErrors.likelyProblem
}
func planB () throws {
print ("planB")
throw ForeseenErrors.unlikelyProblem
}
print ("Hello")
do {
try planA()
}
catch let error as ForeseenError {
print ("catch problem, trying planB")
do {
try planB()
}
catch let error {
print ("Unrecoverable error from planB")
/* if i had a planC() that potentially throws, then i'd
have to put it here in yet another nested do-try-catch
control flow structure */
}
}
catch let error {
print ("Unrecoverable error from planA")
}
print ("EOM")
在swift中,尝试使用catch {}块不会如上所示,而是看起来它需要嵌套到自己的do {}块中。这是看起来像:
#include <stdio.h>
void fun(int *i) {
(*i) = (*i) + 1;
}
int main() {
int pskills[] = { 10, 20, 30, 40, 50 };
int i, *ptr ;
ptr = pskills;
for (i = 0; i < 4; i++) {
fun(ptr++);
printf("%d\n", *ptr);
}
return 0;
}
这对我来说感觉像是反模式,因为它需要任意深度嵌套来处理更多替代方案。此外,虽然我可能需要不同的处理程序来处理尝试序列中不同深度的不可恢复的错误,但一般来说,在最终的catch块中捕获所有错误会更有意义。
社区,关于上述逻辑可以做些什么?