Menu
CoddyTech

Throwing Functions and Catch

Lesson 31 of 48 in Coddy's Swift for C++ Developers course.

C++ functions may throw unless their contract prohibits it, and noexcept concerns whether an exception may escape rather than marking each potentially throwing call. Swift declares throws and marks calls with try. Its do-catch can handle failure, another throwing function can propagate it, and try? converts a thrown failure to an optional absence. Errors conform to Error and need not be class instances. These source examples trim ASCII spaces, while the target Foundation operation handles its chosen whitespace set. Both reject the shown blank input. Do not replace expected recoverable failure with try! merely to satisfy the compiler.

C++

Complete program file: 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

Complete program file: LabelError.swift.

enum LabelError: Error { case empty }

Complete program file: 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
}

Complete program file: main.swift.

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

Challenge

Easy

Implement DivisionError: Error with case zero, and quotient(_ numerator: Int, by denominator: Int) throws -> Int in Functions.swift. Throw zero for denominator 0; otherwise use integer division truncated toward zero. Input has two integers -1000 through 1000. Output the quotient or zero when this error is caught.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in DivisionError.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

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)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for C++ Developers

Practice on your own: Swift playground