Throwing Functions and Catch
Lesson 31 of 48 in Coddy's Swift for PHP Developers course.
PHP throws Throwable objects and catches matching exception or error types. It does not require a throws declaration on the function or a try marker at each potentially throwing call. A narrow catch can handle a known domain failure without swallowing every unrelated runtime error.
Swift throwing functions declare throws, and callers mark a throwing call with try. do/catch handles the error. try? converts failure into an optional result; it is useful when absence is enough information, but it discards the specific error. try! traps when an error is thrown.
Both callers handle the rejected empty title with a fallback. The target's Error-conforming enum makes the domain case explicit, and its call-site try signals the throwing operation. Preserve the required failure cases instead of turning all exceptions into successful empty data.
Complete PHP comparison program:
<?php
declare(strict_types=1);
function title(string $text): string {
if ($text === "") throw new InvalidArgumentException("empty");
return strtoupper($text);
}
try { echo title(""), "\n"; }
catch (InvalidArgumentException $error) { echo "missing title\n"; }
Complete Swift comparison program, compiled from these files:
TitleError.swift
enum TitleError: Error { case empty }Functions.swift
func title(_ text: String) throws -> String {
if text.isEmpty { throw TitleError.empty }
return text.uppercased()
}main.swift
do {
print(try title(""))
} catch {
print("missing title")
}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 PHP 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