Throwing Functions and Catch
Lesson 31 of 48 in Coddy's Swift for Kotlin Developers course.
Kotlin exceptions can propagate without a throws declaration at each function boundary. Swift marks throwing functions with throws and normally requires try at the call site, making possible propagation visible. A do-catch statement handles the error locally; try? converts a failure into nil when losing the error details is acceptable. Swift error values conform to Error, often through an enum that names the failure cases. Avoid try! unless failure is impossible under a proven invariant because it traps when an error is thrown. The example validates an opening bracket and catches a named syntax error without using errors as a substitute for ordinary optional lookup.
Kotlin
class SyntaxFailure : Exception()
fun opening(text: String): String {
if (!text.startsWith("[")) throw SyntaxFailure()
return "open"
}
fun main() {
try { println(opening("x")) } catch (e: SyntaxFailure) { println("syntax") }
println(opening("[a]"))
}Swift
enum SyntaxFailure: Error { case missingBracket }
func opening(_ text: String) throws -> String {
guard text.hasPrefix("[") else { throw SyntaxFailure.missingBracket }
return "open"
}
do { print(try opening("x")) } catch { print("syntax") }
print(try opening("[a]"))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 Kotlin 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