swift - 如何使 Swift 2 函数抛出异常

标签 swift error-handling try-catch swift2

这是我当前的代码

class HelloWorld {
    func foobar() {
        // ...
    }
}

当调用此函数并发生意外情况时,我如何使该函数抛出异常?

最佳答案

根据 Swift 文档:

Throwing Errors

To indicate that a function or method can throw an error, you write the throws keyword in its declaration, after its parameters. If it specifies a return type, you write the throws keyword before the return arrow (->). A function, method, or closure cannot throw an error unless explicitly indicated.

Apple's documentation 中有大量关于此主题的信息

错误是使用枚举表示的,因此通过枚举创建一些您想要的错误,然后使用 throw 关键字来完成。

示例:

enum MyError: ErrorType{
    case FooError
}

func foobar() throws{
   throw MyError.FooError
}

关于swift - 如何使 Swift 2 函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31993665/

相关文章:

TypeScript:如何在 try block 中设置 const 变量?

xcode - 以编程方式快速将 NSClickGestureRecognizer 添加到 NSButton

行操作按钮的快速图像

ios - UINavigationBar 大标题在执行 segues 时不调整大小

java - Java 错误,但没有显示错误位置,我该怎么办?

node.js - 无法理解为什么 try and catch 在 mongoose 中没有按预期工作

ios - 使用 popViewController SWIFT 时调用 viewdidload

ruby - 如何验证ruby cucumber中抛出的异常

java - (Java)学习try catch中的return方法

php - 捕获接口(interface)异常。