Menu
CoddyTech

Throwing Functions and Catch

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

C# methods can throw exceptions without a throws clause. Swift marks a throwing function with throws and marks a potentially throwing call with try. A caller can catch errors with do and catch, propagate them from another throwing function, or intentionally convert failure to an optional with try?. Swift errors are values conforming to Error; they need not be exception class instances. The example rejects an empty label and returns a trimmed nonempty one. Do not mechanically use try! as a way to silence the compiler: it traps if the call throws. Catch the failures you can handle and leave success formatting to the caller.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
static class Labels { public static string Clean(string value) { string s = value.Trim(); if (s.Length == 0) throw new ArgumentException(); return s; } }

class Program
{
    static void Main()
    {
        foreach (string text in new[] { " ok ", " " }) {
            try { Console.WriteLine(Labels.Clean(text)); }
            catch (ArgumentException) { Console.WriteLine("empty"); }
        }
    }
}

Swift

Complete program file: LabelError.swift.

enum LabelError: Error { case empty }

Complete program file: Functions.swift.

import Foundation
func clean(_ value: String) throws -> String {
    let text = value.trimmingCharacters(in: .whitespaces)
    guard !text.isEmpty else { throw LabelError.empty }
    return text
}

Complete program file: main.swift.

for text in [" ok ", " "] {
    do { print(try clean(text)) }
    catch LabelError.empty { print("empty") }
    catch { print("other") }
}
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 C# Developers

Practice on your own: Swift playground