Throwing Functions and Catch
Lesson 31 of 48 in Coddy's Swift for C Developers course.
Standard C has no built-in exception mechanism; APIs commonly return status codes and write successful values through output parameters. Swift throwing functions declare throws, calls use try, and errors conform to Error. A Swift error may be an enum value rather than a class instance.
The C helper returns false for an empty key and only writes its output parameter on success. Swift throws a missing error and handles it with do-catch. An uncaught error can propagate through an appropriately declared function. The source status convention must be checked explicitly rather than treated as successful text.
C: complete program
config.h
#ifndef CONFIG_H
#define CONFIG_H
#include <stdbool.h>
static bool require_key(const char *key, const char **result) {
if (key[0] == '\0') return false;
*result = key;
return true;
}
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "config.h"
int main(void) {
const char *result = NULL;
if (require_key("", &result)) puts(result); else puts("missing");
return 0;
}
Swift: complete program
ConfigError.swift
import Foundation
enum ConfigError: Error { case missing }Functions.swift
import Foundation
func requireKey(_ key: String) throws -> String {
guard !key.isEmpty else { throw ConfigError.missing }
return key
}main.swift
import Foundation
do { print(try requireKey("")) }
catch { print("missing") }Do not translate expected C error returns into forced unwraps or try! automatically. Choose recoverable Swift errors and preserve the documented state on rejection.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for C Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps7Failures and Abstraction
Throwing Functions and CatchResult as a Stored OutcomeProtocols and ConformanceExtensions Add BehaviorGeneric Value ContainersRecap: Validated Batch2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground