如何在catch中打印错误 [英] how to print error in catch

查看:175
本文介绍了如何在catch中打印错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

catch let error as LocksmithError{
print(error)// it would print the case of the error.
}

但是,如果我执行

catch LocksmithError.Duplicate{

}

catch{
print (LocksmithError) // Obviously I would just print LocksmithError, it won't print the case
print (LocksmithError.rawValue) // prints nothing
}

我的问题是:使用第二种方法是有什么我可以实际检索和错误的价值/案例?或者如果我没有在入口点获得价值即catch,那么我错过了这样的机会!

My question is: Using the 2nd approach is there any that I can actually retrieve and the value/case of the error? Or if I don't get the value right at the entry point ie the catch, then I miss the chance of doing it!

推荐答案

p> catch 块是独占案例,按顺序进行评估。当匹配成功时,我们停止

The catch blocks are exclusive cases, evaluated in order. When a match succeeds, we stop.

所以,让我们考虑一下这个结构:

So, let's just think about this structure:

catch LocksmithError.Duplicate {
    // 1
    print("duplicate")
}
catch {
    // 2
    print(error)
}

如果我们在 1 ,那么范围是 LocksmithError.Duplicate

If we are at 1, then what is in scope is the LocksmithError.Duplicate.

如果我们是在 2 ,那么范围是什么,每个其他类型的错误被捕获。没有办法你可以在这里保持 LocksmithError.Duplicate ,因为 它会被 1 我们不会在这里

If we are at 2, then what is in scope is every other kind of error that gets caught. There's no way you can get hold of the LocksmithError.Duplicate here, because ex hypothesi it would have been caught in 1 and we wouldn't be here.

现在,我 的方式是这样做的:

Now, the way I would do it is like this:

catch let err as LocksmithError {
    // 1
    print(err)
}
catch {
    // 2
    print(error)
}

这可能是你之后的事情;它给我们一个价值 err ,将错误带入 1 中的大括号。 (自动错误值只存在最终的catch-all catch 块。)

That may be the sort of thing you are after; it gives us a value err that carries the error into the curly braces in 1. (The automatic error value exists only the final catch-all catch block.)

这篇关于如何在catch中打印错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆