do {
let result = try someThrowingFunction()
print("Result: \(result)")
} catch {
print("Error: \(error)")
}
do
블록: try
구문을 포함해 에러가 발생할 수 있는 코드를 실행try
: 에러를 던질 수 있는(throwing
) 함수 호출 시 반드시 사용catch
: 발생한 에러를 포착해 처리error
: 발생한 에러가 자동으로 전달되는 에러 객체enum MyError: Error {
case invalidInput
case unknown
}
func throwingFunction(value: Int) throws -> String {
if value < 0 {
throw MyError.invalidInput
}
return "Value is \(value)"
}
func testErrorHandling() {
do {
let result = try throwingFunction(value: -1)
print("Success:", result)
} catch MyError.invalidInput {
print("🚫 Error: Invalid input")
} catch {
print("⚠️ Unknown error:", error)
}
}
testErrorHandling()
🚫 Error: Invalid input
throwingFunction(value:)
이 throws
키워드를 사용했으므로, 반드시 try
를 붙여 호출해야 합니다.catch MyError.invalidInput
: 구체적인 에러 타입을 포착해 처리 가능catch
는 모든 기타 에러를 처리nil
을 반환let result = try? throwingFunction(value: -1)
print(result) // 출력: nil
let result = try! throwingFunction(value: 5)
print(result) // 출력: Value is 5
⚠️ 주의: 에러 발생 시 앱이 즉시 종료됩니다.
func safeFunction() {
guard let result = try? throwingFunction(value: 10) else {
print("Invalid result")
return
}
print("Success:", result)
}
safeFunction()
// 출력: Success: Value is 10
func performOperation(_ operation: () throws -> String) rethrows -> String {
return try operation()
}
do {
let result = try performOperation {
throw MyError.unknown
}
print(result)
} catch {
print("Caught error:", error)
}
// 출력: Caught error: unknown
do
-try
-catch
는 에러 처리 시 제어 흐름 기반입니다. 반면, Result
타입은 값 기반으로 에러를 전달합니다.
func throwingFunction(value: Int) throws -> String {
if value < 0 {
throw MyError.invalidInput
}
return "Value is \(value)"
}
let result = Result { try throwingFunction(value: -1) }
switch result {
case .success(let value):
print("Success:", value)
case .failure(let error):
print("Failure:", error)
}
✅ do
-try
-catch
는 명시적인 에러 처리를 위한 구문
✅ try?
와 try!
는 에러 발생 시 옵셔널 반환 또는 크래시 발생
✅ rethrows
는 클로저 에러 전파를 위해 사용
✅ Result
타입은 값 기반 에러 처리로 do-catch
와 상호보완적