Menu
CoddyTech

Throwing Functions and Catch

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

Dart functions can throw without declaring an exception in their signature, and callers do not write try before each call. Swift marks a throwing function with throws; a potentially throwing call uses try and must propagate or handle the error. Swift errors conform to Error. A do/catch statement handles them; try? converts a failure into an optional result, while try! traps if an error occurs. The example rejects an empty title and catches the domain error, rather than relying on an arithmetic failure.

Complete Dart program. Each labelled block is a separate file.

Functions.dart

String requireTitle(String text) {
  if (text.isEmpty) throw FormatException('empty');
  return text.toUpperCase();
}

main.dart

import 'Functions.dart';
void main() {
  try {
    print(requireTitle(''));
  } on FormatException {
    print('missing title');
  }
}

Complete Swift program. Each labelled block is a separate file.

TitleError.swift

import Foundation
enum TitleError: Error { case empty }

Functions.swift

import Foundation
func requireTitle(_ text: String) throws -> String {
    guard !text.isEmpty else { throw TitleError.empty }
    return text.uppercased()
}

main.swift

import Foundation
do {
    print(try requireTitle(""))
} catch {
    print("missing title")
}
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 Dart Developers

Practice on your own: Swift playground