Menu
CoddyTech

抛出错误的函数与捕获

Coddy 面向 C++ 开发者的 Swift 课程 课程的第 31 课,共 48 课。

C++ 函数可能会抛出异常,除非其契约禁止这样做;noexcept 关注的是异常是否可能逃逸,而不是标记每个可能抛出异常的调用。Swift 声明 throws 并使用 try 标记调用。它的 do-catch 可以处理失败,另一个抛出异常的函数可以传播它,而 try? 会将抛出的失败转换为可选值的缺失。错误遵循 Error 协议,不需要是类实例。这些示例修剪了 ASCII 空格,而目标的 Foundation 操作则处理其选定的空白字符集。两者都会拒绝所示的空白输入。不要仅仅为了满足编译器就用 try! 替换预期的可恢复失败。

C++

完整程序文件:main.cpp。

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
std::string clean(const std::string &value) {
    auto first = value.find_first_not_of(' ');
    if (first == std::string::npos) throw std::invalid_argument("empty");
    auto last = value.find_last_not_of(' ');
    return value.substr(first, last - first + 1);
}

int main() {
for (const std::string text : {" ok ", " "}) {
        try { std::cout << clean(text) << '\n'; }
        catch (const std::invalid_argument &) { std::cout << "empty\n"; }
    }
}

Swift

完整程序文件:LabelError.swift。

enum LabelError: Error { case empty }

完整程序文件:Functions.swift。

import Foundation
func clean(_ value: String) throws -> String {
    let text = value.trimmingCharacters(in: .whitespaces)
    guard !text.isEmpty else { throw LabelError.empty }
    return text
}

完整程序文件:main.swift。

for text in [" ok ", " "] {
    do { print(try clean(text)) }
    catch LabelError.empty { print("empty") }
    catch { print("other") }
}
challenge icon

挑战

简单

实现带有 case zero 的 DivisionError: Error,以及在 Functions.swift 中实现 quotient(_ numerator: Int, by denominator: Int) throws -> Int。当分母为 0 时抛出 zero;否则使用向零截断的整数除法。输入包含两个 -1000 到 1000 之间的整数。输出商,或当捕获到该错误时输出 zero。

实现所需的 API 与 solve(_ input: String) -> String。返回输出文本,末尾不带换行符;请勿在可编辑代码中打印。锁定的驱动程序会在额外的有效输入上独立检查 API,然后打印返回的文本,并带有且仅有一个换行符。所有数值运算均保持在 Int 范围内。

你的代码存放在 DivisionError.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,无法编辑。

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
do { guard try quotient(17, by: 4) == 4 else { return false }; do { _ = try quotient(2, by: 0); return false } catch DivisionError.zero { } catch { return false }; return try quotient(-17, by: 4) == -4 } catch { return false }
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 公共 API 探测开始
let apiOK = apiChecks(input)
// 公共 API 探测结束
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C++ 开发者的 Swift 课程中的所有课

自己练习: Swift 在线编辑器