0
0
Swiftprogramming~5 mins

Do-try-catch execution flow in Swift

Choose your learning style9 modes available
Introduction

We use do-try-catch to safely run code that might fail. It helps us handle errors without crashing the program.

When reading a file that might not exist.
When converting user input to a number that might be invalid.
When calling a function that can throw an error.
When working with network requests that might fail.
Syntax
Swift
do {
    try someFunctionThatThrows()
    // code if no error
} catch {
    // code to handle error
}

do starts a block where errors can be caught.

try is used before a function that can throw an error.

Examples
Try to read a file. If it fails, print an error message.
Swift
do {
    try readFile()
    print("File read successfully")
} catch {
    print("Failed to read file")
}
Try to convert input. Catch error if conversion fails.
Swift
do {
    try convertInputToNumber()
    print("Conversion succeeded")
} catch {
    print("Conversion failed")
}
Sample Program

This program checks if a number is negative. If it is, it throws an error. The do-try-catch block catches the error and prints a message.

Swift
import Foundation

enum SimpleError: Error {
    case badNumber
}

func checkNumber(_ number: Int) throws {
    if number < 0 {
        throw SimpleError.badNumber
    }
}

do {
    try checkNumber(-5)
    print("Number is good")
} catch {
    print("Caught an error: number is negative")
}
OutputSuccess
Important Notes

You must use try before calling a function that can throw an error.

The catch block runs only if an error happens inside do.

You can have multiple catch blocks to handle different errors.

Summary

Use do-try-catch to handle errors safely.

try marks code that might fail.

catch handles errors without crashing.