exception - 有什么办法可以在 Swift 中捕获断言吗?

标签 exception try-catch assert swift

似乎 Swift 没有类似 C#/Java 的异常,而是使用断言。然而,书中说,在生产环境中,他们会立即使应用程序崩溃。没有办法解决吗?单元测试呢?我如何测试某个函数断言它获得了正确的输入值?

最佳答案

如您所述,断言会使您的应用在调试或生产中崩溃。它们并非旨在像 Java/C# 异常那样发挥作用。他们唯一的真正目的是:

Use an assertion whenever a condition has the potential to be false, but must definitely be true in order for your code to continue execution. ... in situations where invalid conditions are possible, an assertion is an effective way to ensure that such conditions are highlighted and noticed during development, before your app is published.

由于您可以在 Swift 中使用 Cocoa 类,因此您仍然可以使用 NSException 来处理您的代码可以处理的异常情况。

关于exception - 有什么办法可以在 Swift 中捕获断言吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24003824/

相关文章:

c++ - 如何在不使用 abort() 的情况下断言()?

c++ - 在 C++ 中使用函数签名后抛出的目的是什么?

python - 复制文件时使用 try/except 或 if/else

javascript - Bluebird promise 并捕获分支

c++ - 如何从多线程应用程序中的断言失败中优雅退出

assert.h 中的 C++ 断言实现

Java 捕获异常和子类

java - JOptionPane 中的文本换行?

c# - 使用未分配的局部变量。却总是陷入assignment

c++ - C++ 库中更优雅的错误处理 - jsoncpp