Menu
CoddyTech

Throwing Functions and Catch

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

Java distinguishes checked exceptions, which callers must catch or declare, from unchecked exceptions such as IllegalArgumentException. Swift has no equivalent checked-versus-unchecked class hierarchy for errors: a throwing call is marked with try, and errors conform to Error.

The examples reject a missing configuration key. Java declares a checked exception in the method signature. Swift marks the function throws and uses do-catch to handle failure. A Swift error can be an enum value; it need not inherit from a class. A function can propagate a thrown error instead of catching it locally.

Java: complete program

MissingKey.java

public class MissingKey extends Exception {}

Main.java

import java.util.*;
import java.util.function.*;
public class Main {
  static String requireKey(String key) throws MissingKey {
    if (key.isEmpty()) throw new MissingKey();
    return key;
  }
  public static void main(String[] args) throws Exception {
    try { System.out.println(requireKey("")); }
    catch (MissingKey error) { System.out.println("missing"); }
  }
}

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") }

Swift throws is part of the function type and call syntax. Do not assume all Java RuntimeException paths should become forced unwraps or try!; model recoverable errors deliberately.

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 Java Developers

Practice on your own: Swift playground