Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The throw statement is a control flow mechanism used to raise an error and immediately transfer program execution to the nearest enclosing error-handling scope. When executed, it halts the current execution path and propagates an error value up the call stack until it is caught by a do-catch block.
throw expression
The expression evaluated by the throw statement must conform to the Swift.Error protocol. Because Error is an empty marker protocol, the expression is typically an enumeration case, though structures and classes conforming to Error are also valid operands.

Execution Mechanics

When the Swift compiler encounters a throw statement, the following sequence occurs:
  1. Evaluation: The expression following the throw keyword is evaluated to produce an error instance.
  2. Control Transfer: Standard linear execution is immediately aborted. Any statements following the throw statement within the same lexical scope become unreachable.
  3. Propagation: The runtime searches for the nearest enclosing catch clause that matches the thrown error type. If the throw statement is not wrapped in a local do-catch block, the error propagates out of the current function, method, or closure.

Contextual Requirements

To legally use a throw statement that propagates out of its immediate scope, the enclosing callable (function, method, or closure) must be explicitly annotated with the throws keyword in its signature.
enum OperationError: Error {
    case invalidState
    case constraintViolation(code: Int)
}

// The 'throws' keyword is required because the 'throw' statement 
// propagates the error out of the function scope.
func executeOperation(condition: Int) throws {
    if condition < 0 {
        throw OperationError.constraintViolation(code: condition)
    }
    
    if condition == 0 {
        throw OperationError.invalidState
    }
    
    // Unreachable if either throw statement executes
}

Typed Throws (Swift 6.0+)

By default, the throw statement propagates an existential any Error. However, if the enclosing function specifies a typed throw in its signature, the compiler enforces that the throw statement’s operand strictly matches the specified error type.
func executeStrictOperation() throws(OperationError) {
    // The compiler guarantees only OperationError can be thrown here
    throw .invalidState 
}

Interaction with Defer

Before the throw statement transfers control out of the current scope, any defer blocks defined within that scope are executed in reverse order of their definition. This guarantees that cleanup routines run regardless of whether the scope exits via a standard return or an abrupt throw.
Master Swift with Deep Grasping Methodology!Learn More