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

Error Protocol की जानकारी

Error protocol एक label है जिसे आप अपने custom type पर डालते हैं यह कहने के लिए "यह represent करता है कि कुछ गलत हो गया है।"
Syntax
swift
enum ErrorName: Error {
    case simpleCase
    case caseWithData(label: Type)
}

Defining a Custom Error Type

किसी enum को Error conform करना इसके हर case को एक distinct, throwable error value में बदल देता है।

उदाहरण: Defining a Custom Error Type

markup
// Define an enum `ValidationError` listing its possible cases
enum ValidationError: Error {
    // Case `tooShort`
    case tooShort
    // Case `tooLong`
    case tooLong
}
// Declare a constant `error`, set to `ValidationError.tooShort`
let error = ValidationError.tooShort
// Print `error` to the console
print(error)

Errors with Associated Values

बिल्कुल किसी और enum की तरह, एक error type associated values रख सकता है यह ज़्यादा detail प्रदान करने के लिए कि क्या गलत हुआ।

उदाहरण: Errors with Associated Values

markup
// Define an enum `ValidationError` listing its possible cases
enum ValidationError: Error {
    // Case `tooShort`
    case tooShort(minimum: Int)
    // Case `tooLong`
    case tooLong(maximum: Int)
}
// Declare a constant `error`, set to `ValidationError.tooShort(minimum: 5)`
let error = ValidationError.tooShort(minimum: 5)
// Print `error` to the console
print(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. यह भूल जाना कि throw से throw किए जाने से पहले एक error type को खाली Error protocol conform करना चाहिए।
  2. एक proper enum के बजाय एक plain String या generic type को error के रूप में उपयोग करना जो Error conform करता है, type-safety और क्या गलत हो सकता है उसकी clarity खोते हुए।
  3. per domain अलग, focused error types के बजाय एक giant enum में कई unrelated error cases define करना।
चैप्टर सारांश
  • कोई भी type Error protocol conform करके एक error represent कर सकता है।
  • Enums related error cases का एक set define करने का सबसे आम तरीका हैं।
  • Error में खुद कोई requirements नहीं -- यह एक marker protocol है।
  • एक अच्छे design वाला error type बिल्कुल बताता है कि किसी दी operation में क्या गलत हो सकता है।
🔒

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.