Error Handling Questions with Answers

12 practice questions on Error Handling (iOS (Swift & SwiftUI)) with answers and step-by-step solutions. Try 10 samples below, then practise all 12 free in the AptiNest app.

Sample questions

Question 1Easy

What happens if the call in try! loadConfig() throws an error?

  1. The error goes to the nearest catch block
  2. The app crashes with a runtime error
  3. The error is logged and execution continues
  4. The result becomes nil

Answer: B. The app crashes with a runtime error

Explanation

try! asserts that no error will be thrown. If one is, the program traps, so use it only when failure is impossible.

Step-by-step solution

  1. try! means you promise no error will occur.
  2. If the call throws, the program traps.
  3. So the app crashes.

Why the other options are wrong

  • A. try! does not route to catch.
  • C. Errors are not logged and skipped.
  • D. try? gives nil, not try!.

Tip: ! = crash on failure.

Question 2Easy

How do you call a function declared as func load() throws -> Data?

  1. Add a throws keyword after the call
  2. Wrap the call in an if let statement
  3. Call it normally; Swift catches errors automatically
  4. Use try, inside do/catch or a throwing function

Answer: D. Use try, inside do/catch or a throwing function

Explanation

Calls to throwing functions must be marked with try, and the error must be handled by do/catch or passed on by a function that also throws.

Step-by-step solution

  1. Calling a throwing function requires using try keyword.
  2. Try must be inside do/catch block or another throwing function.
  3. Normal call without try will not handle errors properly.
  4. Swift does not automatically catch errors from throwing functions.
  5. Correct way is to use try inside appropriate error handling structure.
  6. Final answer: Use try, inside do/catch or a throwing function.

Why the other options are wrong

  • A. throws is written in the declaration, not added after a call.
  • B. if let unwraps optionals, but a throwing call's error is not an optional.
  • C. Swift never catches errors on its own; a throwing call must be marked with try.

Tip: Always use try when calling throwing functions and handle errors properly.

Question 3Easy

Which protocol must a type adopt to be thrown as an error in Swift?

  1. Throwable
  2. Exception
  3. LocalizedError only
  4. Error

Answer: D. Error

Explanation

Any type conforming to Error can be thrown; enums are the common choice. LocalizedError refines Error with user-facing messages but isn't required.

Step-by-step solution

  1. To throw an error, a type must adopt the Error protocol.
  2. The Error protocol is the base for all errors in Swift.
  3. LocalizedError is a protocol that refines Error, but it is not required.
  4. Thus, any type conforming to Error can be thrown.
  5. The correct answer is Error.

Why the other options are wrong

  • A. Throwable is not a Swift protocol; Swift uses Error for thrown values.
  • B. Exception is a Java-style name and not a Swift protocol; use Error.
  • C. LocalizedError only adds message text and builds on Error, so Error is the base requirement.

Tip: Remember: Error is the base protocol for all throwable types in Swift.

Question 4Easy

What does try? do?

  1. It retries the call once if an error is thrown
  2. It ignores the error and returns the type's default value
  3. It gives an optional: nil if an error is thrown
  4. It crashes the app when an error is thrown

Answer: C. It gives an optional: nil if an error is thrown

Explanation

try? converts the call into an optional: the value on success, nil on any error, and the error itself is discarded.

Step-by-step solution

  1. Try? runs the call and turns any thrown error into nil.
  2. A successful result is wrapped in an optional.
  3. So try? gives an optional that is nil when an error is thrown, which is option C.

Why the other options are wrong

  • A. Try? does not retry the call.
  • B. It returns nil, not the type's default value.
  • D. Try? does not crash; it hides the error.

Tip: Try? is a quick way to turn a throwing call into an optional.

Question 5Medium

What does rethrows mean in func apply(_ f: () throws -> Int) rethrows -> Int?

  1. apply catches and rethrows every error twice
  2. It throws only when the closure f throws
  3. apply can never throw, even if f does
  4. apply converts errors into optionals

Answer: B. It throws only when the closure f throws

Explanation

A rethrows function only propagates errors from its function arguments. Called with a non-throwing closure, it needs no try, which is how map and filter work.

Step-by-step solution

  1. Rethrows means the function can throw if its argument throws.
  2. Apply uses rethrows to pass through errors from closure f.
  3. If closure f throws, apply will also throw that error.
  4. If closure f does not throw, apply does not throw either.
  5. So rethrows only throws when the closure f throws.

Why the other options are wrong

  • A. apply does not catch and rethrow errors twice; it passes the closure's error through once.
  • C. apply can throw whenever f throws, so the claim that it can never throw is false.
  • D. apply does not turn errors into optionals; it rethrows the error itself.

Tip: Rethrows lets the function throw if the closure throws, otherwise it's safe.

Question 6Medium

What is the output?

enum E: Error { case bad }
func f(_ x: Int) throws -> Int {
    if x < 0 { throw E.bad }
    return x
}
do {
    _ = try f(-1)
    print("ok")
} catch E.bad {
    print("bad")
} catch {
    print("other")
}
  1. other
  2. bad other
  3. bad
  4. ok

Answer: C. bad

Explanation

f(-1) throws E.bad, so "ok" is skipped and the first matching catch pattern catch E.bad runs. Only one catch clause runs.

Step-by-step solution

  1. f(-1) throws E.bad because -1 < 0.
  2. The do block catches E.bad and prints 'bad'.
  3. Other catch clauses are not executed.
  4. Only the first matching catch runs, so output is 'bad'.

Why the other options are wrong

  • A. other is wrong: the first catch clause matches E.bad, so the general catch is skipped.
  • B. Only one catch runs, so the output is bad, not bad plus other.
  • D. ok is not printed, because f(-1) throws before the print line runs.

Tip: Always check the order of catch clauses in error handling.

Question 7Medium

In a final catch block with no pattern (catch { ... }), how do you get at the error that was thrown?

  1. By calling Error.current()
  2. Through the implicit local constant error
  3. It cannot be accessed without a pattern
  4. Through a global variable named lastError

Answer: B. Through the implicit local constant error

Explanation

A catch clause without a pattern binds the thrown value to a local constant named error.

Step-by-step solution

  1. Catch block without pattern binds error to local constant 'error'.
  2. Use 'error' variable inside catch block to access thrown value.
  3. No need for additional functions or global variables.
  4. Access error details via 'error' in the catch clause.
  5. Final answer: Through the implicit local constant error.

Why the other options are wrong

  • A. Error.current() does not exist in Swift; the error is a local constant in the catch.
  • C. The error is available through the implicit error constant even with no pattern.
  • D. lastError is not a global Swift variable; the error is a local constant in the catch.

Tip: Remember: no pattern in catch binds error to 'error' variable.

Question 8Medium

What is Swift's Result type?

  1. A protocol every throwing function returns
  2. A struct that bundles a value with an optional error
  3. A class that retries an operation until it succeeds
  4. An enum with success(Value) and failure(Error) cases

Answer: D. An enum with success(Value) and failure(Error) cases

Explanation

Result<Success, Failure: Error> stores either outcome as a value, which is useful for completion handlers and for storing results to handle later.

Step-by-step solution

  1. Result type is an enum with two cases.
  2. One case is success(Value) holding the result.
  3. Other case is failure(Error) holding an error.
  4. It represents either a successful value or an error.
  5. This matches option D exactly.

Why the other options are wrong

  • A. Result is an enum, not a protocol, and throwing functions do not return it.
  • B. Result is an enum with success and failure cases, not a struct with an optional error.
  • C. Result does not retry anything; it only holds a success value or an error.

Tip: Remember Result is an enum with success and failure cases for handling operations safely.

Question 9Hard

A network request can fail because the connection drops. Which approach fits Swift's error-handling model?

  1. Use precondition() to check the connection first
  2. Force-unwrap the response and let it crash if missing
  3. Call fatalError() so the bug is noticed in testing
  4. Throw an error the caller can catch and recover from

Answer: D. Throw an error the caller can catch and recover from

Explanation

Throwing is for recoverable conditions such as I/O and network failures. fatalError and precondition are for programmer errors that should never happen.

Step-by-step solution

  1. Throwing an error allows the caller to handle it gracefully.
  2. Network failures are recoverable, so throwing is appropriate.
  3. Force-unwrapping leads to crashes and isn't recoverable.
  4. fatalError() is for bugs, not external errors like network drops.
  5. Swift's model uses throw/catch for external errors like this.

Why the other options are wrong

  • A. precondition is for programmer bugs, not for checking a network connection that can drop.
  • B. Force-unwrapping a missing response crashes the app, which is the wrong response to a network failure.
  • C. fatalError stops the program, and it is for bugs, not for network failures.

Tip: Use throw/catch for external errors, fatalError() for internal bugs.

Question 10Hard

What is the output?

enum E: Error { case bad }
func h() throws {
    defer { print("cleanup") }
    print("work")
    throw E.bad
}
do { try h() } catch { print("caught") }
  1. work cleanup caught
  2. work caught cleanup
  3. cleanup work caught
  4. work caught

Answer: A. work cleanup caught

Explanation

defer runs whenever the scope exits, including when an error is thrown. So "cleanup" prints before the error reaches the caller's catch block.

Step-by-step solution

  1. H prints work first, then throws E.bad.
  2. The defer is still scheduled, so it runs as h exits and prints cleanup.
  3. The catch block in the caller then prints caught.
  4. Output is work cleanup caught, so the answer is option A.

Why the other options are wrong

  • B. The defer runs when h exits, before the catch block.
  • C. Work is printed first, since the body runs before the defer.
  • D. Cleanup is printed too; defers run even when an error is thrown.

Tip: Defers still run when a function exits by throwing.

Practise all 12 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all iOS (Swift & SwiftUI) topics · All topics