0
0
Swiftprogramming~5 mins

Throwing functions with throws in Swift

Choose your learning style9 modes available
Introduction

Sometimes a function might fail to do its job. Using throws lets the function tell you when something goes wrong.

When reading a file that might not exist.
When converting a string to a number that might be invalid.
When making a network request that could fail.
When checking user input that might be incorrect.
Syntax
Swift
func functionName() throws -> ReturnType {
    // code that might throw an error
}

Use throws after the function parentheses to mark it as a throwing function.

Calling a throwing function requires handling errors with try.

Examples
A simple throwing function that returns a string or throws an error.
Swift
func readFile() throws -> String {
    // might throw an error if file not found
    return "file content"
}
This function throws an error if you try to divide by zero.
Swift
enum DivisionError: Error {
    case divisionByZero
}

func divide(_ a: Int, by b: Int) throws -> Int {
    if b == 0 {
        throw DivisionError.divisionByZero
    }
    return a / b
}
Sample Program

This program defines a throwing function divide that throws an error if dividing by zero. It then calls this function twice: once with valid input and once with zero as the divisor. The errors are caught and handled with do-catch.

Swift
enum DivisionError: Error {
    case divisionByZero
}

func divide(_ a: Int, by b: Int) throws -> Int {
    if b == 0 {
        throw DivisionError.divisionByZero
    }
    return a / b
}

// Using the throwing function

func testDivision() {
    do {
        let result = try divide(10, by: 2)
        print("Result: \(result)")
    } catch DivisionError.divisionByZero {
        print("Error: Cannot divide by zero.")
    } catch {
        print("Unexpected error: \(error)")
    }

    do {
        let result = try divide(10, by: 0)
        print("Result: \(result)")
    } catch DivisionError.divisionByZero {
        print("Error: Cannot divide by zero.")
    } catch {
        print("Unexpected error: \(error)")
    }
}

testDivision()
OutputSuccess
Important Notes

Throwing functions must be called with try, try?, or try!.

Use do-catch blocks to handle errors gracefully.

Errors must conform to the Error protocol.

Summary

Use throws to mark functions that can fail.

Call throwing functions with try and handle errors with do-catch.

Define errors by creating types that conform to Error.