Skip to content
Learn Netverks

Lesson

Step 24/36 67% through track

error-handling-swift

Error handling

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Error handling: the syntax, patterns, and safety habits you need before advancing in Swift.

Teams still ship Error handling in Swift codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Error handling in contexts like: iPhone/iPad/Mac apps, server-side Swift (niche), and Apple toolchain projects.

Write Swift in main.swift with print(), click Run on server—the dev runner swiftc compiles and runs the binary (requires Swift toolchain, typically macOS; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Swift models recoverable failures with throws, try, and typed errors conforming to Error—unlike exceptions in Java, errors are part of the function signature and must be handled explicitly.

Defining and throwing

enum ParseError: Error {
    case invalidInput
    case outOfRange
}

func parse(_ text: String) throws -> Int {
    guard let value = Int(text) else { throw ParseError.invalidInput }
    return value
}

try, try?, try!

do {
    let n = try parse("42")
    print(n)
} catch {
    print("failed: \(error)")
}

try? converts to optional; try! force-unwraps—avoid in production.

Important interview questions and answers

  1. Q: throws vs Result?
    A: throws integrates with do/catch; Result<Success, Failure> suits async callbacks and functional pipelines—often combined with async/await.
  2. Q: Checked vs unchecked?
    A: Swift errors are typed and propagated via try—callers must handle or rethrow; unlike Java checked exceptions but more explicit than optional-only returns.

Self-check

  1. What does try? return on failure?
  2. How do you define a custom error type?

Pitfall: Avoid try! in production—crashes on unexpected errors like force unwrap.

Interview prep

try? result?

Converts to optional nil on failure.

throws vs Result?

throws integrates with do/catch; Result suits functional pipelines.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • throws vs Result?
  • try? vs try!?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump