खोज…


टिप्पणियों

त्रुटियों के बारे में अधिक जानकारी के लिए, स्विफ्ट प्रोग्रामिंग भाषा देखें

मूल बातें संभालने में त्रुटि

स्विफ्ट में कार्य मान लौटा सकते हैं, त्रुटियां फेंक सकते हैं , या दोनों:

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

कोई भी मान जो ErrorType प्रोटोकॉल के अनुरूप है (NSError ऑब्जेक्ट सहित) को त्रुटि के रूप में फेंका जा सकता है। Enumerations कस्टम त्रुटियों को परिभाषित करने के लिए एक सुविधाजनक तरीका प्रदान करते हैं:

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 / throw , और try साथ नियंत्रित किया जाता है।

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 {
    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? , या 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
}

डो-कैच सिंटैक्स एक फेंकी हुई त्रुटि को पकड़ने की अनुमति देता है, और स्वचालित रूप से catch ब्लॉक में उपलब्ध निरंतर नाम error बनाता है:

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

आप स्वयं एक चर भी घोषित कर सकते हैं:

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

विभिन्न catch स्टेटमेंट को चेन करना भी संभव है। यह सुविधाजनक है यदि Do ब्लॉक में कई प्रकार की त्रुटियां डाली जा सकती हैं।

यहां डू-कैच पहले 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
    }
}

त्रुटि प्रसार को अक्षम करना

स्विफ्ट के रचनाकारों ने भाषा को अभिव्यंजक बनाने में बहुत ध्यान दिया है और त्रुटि से निपटने के लिए वास्तव में, अभिव्यंजक है। यदि आप किसी फ़ंक्शन को त्रुटि को फेंकने का प्रयास करते हैं, तो फ़ंक्शन कॉल को कोशिश कीवर्ड से पहले करने की आवश्यकता है। ट्राई कीवर्ड जादुई नहीं है। यह सब करता है, डेवलपर को फ़ंक्शन की फेंकने की क्षमता से अवगत कराता है।

उदाहरण के लिए, निम्न कोड एक 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