← Back to Swift Course | Chapter 11: Error Handling | Lesson 2 of 6

throw, try और catch

throw यह कहने के लिए हाथ उठाना है कि कुछ गलत हो गया, try कुछ ऐसा करने की कोशिश है जो fail हो सकता है, और catch वह है जो fail होने पर इसे handle करता है।
Syntax
swift
func functionName() throws -> ReturnType {
    throw ErrorName.caseName
}

do {
    let result = try functionName()
} catch ErrorName.caseName {
    // handle specific error
} catch {
    // handle any other error
}

Declaring and Throwing an Error

throws चिह्नित एक function throw उपयोग कर सकता है कुछ गलत होने पर normally return करने के बजाय एक error raise करने के लिए।

उदाहरण: Declaring and Throwing an Error

markup
// Define an enum `ValidationError` listing its possible cases
enum ValidationError: Error {
    // Case `empty`
    case empty
}
func validate(_ text: String) throws -> String {
    // Check whether `text.isEmpty`
    if text.isEmpty {
        throw ValidationError.empty
    }
    // Return `text` from this function
    return text
}
do {
    // Declare a constant `result`, set to `try validate("Hello")`
    let result = try validate("Hello")
    // Print "Valid: \(result)" to the console
    print("Valid: \(result)")
} catch {
    // Print "Validation failed: \(error)" to the console
    print("Validation failed: \(error)")
}

Handling Multiple Error Cases

कई catch clauses order में specific error cases match कर सकते हैं, एक switch statement के similar, एक final unmatched catch को fallback के रूप में साथ।

उदाहरण: Handling Multiple Error Cases

markup
// Define an enum `ValidationError` listing its possible cases
enum ValidationError: Error {
    // Case `empty`
    case empty
    // Case `tooShort`
    case tooShort
}
func validate(_ text: String) throws -> String {
    // Check whether `text.isEmpty { throw ValidationError.empty }`
    if text.isEmpty { throw ValidationError.empty }
    // Check whether `text.count < 3 { throw ValidationError.tooShort }`
    if text.count < 3 { throw ValidationError.tooShort }
    // Return `text` from this function
    return text
}
do {
    // Declare a constant `result`, set to `try validate("hi")`
    let result = try validate("hi")
    // Print "Valid: \(result)" to the console
    print("Valid: \(result)")
} catch ValidationError.empty {
    // Print "Text was empty" to the console
    print("Text was empty")
} catch ValidationError.tooShort {
    // Print "Text was too short" to the console
    print("Text was too short")
} catch {
    print("Unknown error")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी ऐसे function को इसके signature में throws चिह्नित करना भूल जाना जो throw कर सकता है -- Swift आपको एक non-throwing function से throw नहीं करने देगा।
  2. एक throwing function को इसके आगे try के बिना call करना; एक throwing function की हर call को try, try?, या try! से prefix किया जाना चाहिए।
  3. एक catch block लिखना जो किसी specific error case से match नहीं करता; आखिर में एक plain catch एक catch-all की तरह काम करता है, लेकिन एक mismatched typed catch बस fall through करता है।
चैप्टर सारांश
  • एक function जो fail हो सकता है उसे इसके parameter list के बाद throws से चिह्नित किया जाता है।
  • throw someError एक error raise करता है, current function के normal execution को रोकते हुए।
  • एक throwing function call करने के लिए try चाहिए, और call आमतौर पर do { } catch { } में wrapped होती है।
  • कई catch blocks specific error cases match कर सकते हैं, एक switch के similar।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.