如何在Swift中使用试捕?
我知道如何创建自己的错误,并使用如何在Swift中使用试捕?,swift,try-catch,Swift,Try Catch,我知道如何创建自己的错误,并使用throws关键字在Swift中触发它们。我不明白的是如何为未处理的异常复制其他语言中的常规try-catch(或Rubyrescue) 示例(Swift): 下面是我在C#中的处理方法,例如: int DivideStuff(int a, int b) { int result; try { result = a / b; } catch { result = 0; } return result; } 如何使用Sw
throws
关键字在Swift中触发它们。我不明白的是如何为未处理的异常复制其他语言中的常规try-catch
(或Rubyrescue
)
示例(Swift):
下面是我在C#中的处理方法,例如:
int DivideStuff(int a, int b) {
int result;
try {
result = a / b;
}
catch {
result = 0;
}
return result;
}
如何使用Swift实现同样的功能?在Swift中,没有捕获任意运行时错误的功能。
开发人员负责正确处理错误 比如说
func divideStuff(a : Int, b : Int) -> Int {
if b == 0 { return 0 }
return a / b
}
您也可以这样处理它:
enum MyErrors: ErrorType {
case DivisionByZero
}
func divideStuff(a: Int, by: Int) throws -> Int {
if by == 0 {
throw MyErrors.DivisionByZero
}
return a / by
}
let result: Int
do {
result = try divideStuff(10, by: 0)
} catch {
// ...
}
这是
do
<文档中的code>catch:您无法使用try/catch捕捉任意运行时异常(如被零除),比较类似的问题和文档链接。谢谢。我不知道Swift不能捕捉任意的运行时错误。不知何故,这感觉有些奇怪。这并不能真正解释try/catch-这很好,但它是防御性编程。您可能希望在do/catch语句中添加一个catch-let错误作为NSError,以便在catch部分中识别错误
enum MyErrors: ErrorType {
case DivisionByZero
}
func divideStuff(a: Int, by: Int) throws -> Int {
if by == 0 {
throw MyErrors.DivisionByZero
}
return a / by
}
let result: Int
do {
result = try divideStuff(10, by: 0)
} catch {
// ...
}