수색…


비고

오류에 대한 자세한 내용은 Swift 프로그래밍 언어를 참조하십시오.

오류 처리 기본 사항

Swift의 함수는 값을 반환하거나, 에러를 던지 거나, 두 가지 모두를 반환 할 수 있습니다.

func reticulateSplines()                // no return value and no error
func reticulateSplines() -> Int         // always returns a value
func reticulateSplines() throws         // no return value, but may throw an error
func reticulateSplines() throws -> Int  // may either return a value or throw an error

오류 유형 프로토콜 (NSError 오브젝트 포함)을 준수하는 값은 오류로 던져 질 수 있습니다. 열거 형 은 사용자 정의 오류를 정의하는 편리한 방법을 제공합니다.

2.0 2.2
enum NetworkError: ErrorType {
    case Offline
    case ServerError(String)
}
3.0
enum NetworkError: Error {
    // Swift 3 dictates that enum cases should be `lowerCamelCase`
    case offline
    case serverError(String)
}

오류는 프로그램 실행 중 치명적이지 않은 오류를 나타내며 특수 제어 흐름 구조 do / catch , throwtry 됩니다.

func fetchResource(resource: NSURL) throws -> String {
    if let (statusCode, responseString) = /* ...from elsewhere...*/ {
        if case 500..<600 = statusCode {
            throw NetworkError.serverError(responseString)
        } else {
            return responseString
        }
    } else {
        throw NetworkError.offline
    }
}

do / catch 사용 do 오류를 발견 할 수 있습니다.

do {
    let response = try fetchResource(resURL)
    // If fetchResource() didn't throw an error, execution continues here:
    print("Got response: \(response)")
    ...
} catch {
    // If an error is thrown, we can handle it here.
    print("Whoops, couldn't fetch resource: \(error)")
}

오류 던질 수있는 함수는 try 사용하여 호출 해야합니다 . try? , 또는 try! :

// error: call can throw but is not marked with 'try'
let response = fetchResource(resURL)

// "try" works within do/catch, or within another throwing function:
do {
    let response = try fetchResource(resURL)
} catch {
    // Handle the error
}

func foo() throws {
    // If an error is thrown, continue passing it up to the caller.
    let response = try fetchResource(resURL)
}

// "try?" wraps the function's return value in an Optional (nil if an error was thrown).
if let response = try? fetchResource(resURL) {
    // no error was thrown
}

// "try!" crashes the program at runtime if an error occurs.
let response = try! fetchResource(resURL)

다른 오류 유형 잡기

이 예제에서 우리 자신의 에러 타입을 만들어 보자.

2.2
enum CustomError: ErrorType {
    case SomeError
    case AnotherError
}

func throwing() throws {
    throw CustomError.SomeError
}
3.0
enum CustomError: Error {
    case someError
    case anotherError
}

func throwing() throws {
    throw CustomError.someError
}

Do-Catch 구문은 throw 된 오류를 잡아 catch 블록에서 사용할 수있는 error 라는 상수를 자동으로 만듭니다.

do {
    try throwing()
} catch {
    print(error)
}

직접 변수를 선언 할 수도 있습니다.

do {
    try throwing()
} catch let oops {
    print(oops)
}

다른 catch 문을 연결할 수도 있습니다. Do 블록에 몇 가지 유형의 오류가 발생할 수있는 경우 편리합니다.

여기서 Do-Catch는 오류를 CustomError 로 캐스팅하려고 시도하고, 사용자 정의 유형이 일치하지 않으면 오류를 NSError 로 캐스팅합니다.

2.2
do {
    try somethingMayThrow()
} catch let custom as CustomError {
    print(custom)
} catch let error as NSError {
    print(error)
}
3.0

스위프트 3에서는 명시 적으로 NSError로 다운 캐스트 할 필요가 없습니다.

do {
    try somethingMayThrow()
} catch let custom as CustomError {
    print(custom)
} catch {
    print(error)
}

명시 적 오류 처리를위한 캐치 및 전환 패턴

class Plane {
    
    enum Emergency: ErrorType {
        case NoFuel
        case EngineFailure(reason: String)
        case DamagedWing
    }

    var fuelInKilograms: Int

    //... init and other methods not shown

    func fly() throws {
        // ...
        if fuelInKilograms <= 0 {
            // uh oh...
            throw Emergency.NoFuel
        }
    }

}

클라이언트 클래스에서 :

let airforceOne = Plane()
do {
    try airforceOne.fly()
} catch let emergency as Plane.Emergency {
    switch emergency {
    case .NoFuel:
        // call nearest airport for emergency landing
    case .EngineFailure(let reason):
        print(reason) // let the mechanic know the reason
    case .DamagedWing:
        // Assess the damage and determine if the president can make it
    }
}

오류 확산 비활성화

Swift의 제작자는 표현의 표현력을 높이기 위해 많은주의를 기울였으며 오류 처리는 표현력이 뛰어납니다. 오류를 발생시킬 수있는 함수를 호출하려고하면 함수 호출 앞에 try 키워드가 있어야합니다. try 키워드는 마법 같은 것이 아닙니다. 그것이하는 모든 일은 개발자가 함수의 throwing 능력을 인식하게합니다.

예를 들어, 다음 코드는 주어진 경로에서 이미지 리소스를로드하거나 이미지를로드 할 수없는 경우 오류를 throw하는 loadImage (atPath :) 함수를 사용합니다. 이 경우 이미지가 응용 프로그램과 함께 제공되므로 런타임에 오류가 발생하지 않으므로 오류 전파를 사용하지 않는 것이 좋습니다.

let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")

현지화 된 설명으로 사용자 정의 오류 만들기

enum 사용자 정의 오류 만들기

enum RegistrationError: Error {
    case invalidEmail
    case invalidPassword
    case invalidPhoneNumber
}

지역화 된 설명을 처리 할 수있는 RegistrationError extension 을 만듭니다.

extension RegistrationError: LocalizedError {
    public var errorDescription: String? {
        switch self {
        case .invalidEmail:
            return NSLocalizedString("Description of invalid email address", comment: "Invalid Email")
        case .invalidPassword:
            return NSLocalizedString("Description of invalid password", comment: "Invalid Password")
        case .invalidPhoneNumber:
            return NSLocalizedString("Description of invalid phoneNumber", comment: "Invalid Phone Number")
        }
    }
}

오류 처리 :

let error: Error = RegistrationError.invalidEmail
print(error.localizedDescription)


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow