Error Handling
Throwing Functions
Functions marked with throws can stop normal execution and report an error.
Reject invalid input
throwing_functions.swift
enum ScoreError: Error {
case belowMinimum
}
func checkedScore(_ score: Int) throws -> String {
if score < 0 {
throw ScoreError.belowMinimum
}
return "score=\(score)"
}
let rawScore =
let message: String
do {
message = try checkedScore(rawScore)
} catch ScoreError.belowMinimum {
message = "score rejected"
}
print(message)
enum ScoreError: Error {
case belowMinimum
}
func checkedScore(_ score: Int) throws -> String {
if score < 0 {
throw ScoreError.belowMinimum
}
return "score=\(score)"
}
let rawScore =
let message: String
do {
message = try checkedScore(rawScore)
} catch ScoreError.belowMinimum {
message = "score rejected"
}
print(message)
enum ScoreError: Error {
case belowMinimum
}
func checkedScore(_ score: Int) throws -> String {
if score < 0 {
throw ScoreError.belowMinimum
}
return "score=\(score)"
}
let rawScore =
let message: String
do {
message = try checkedScore(rawScore)
} catch ScoreError.belowMinimum {
message = "score rejected"
}
print(message)
throwing function
A throwing function uses `throw` to leave the normal path when it cannot produce a valid result.