Error Protocol की जानकारी
Error protocol एक label है जिसे आप अपने custom type पर डालते हैं यह कहने के लिए "यह represent करता है कि कुछ गलत हो गया है।"
In this page:
Syntax
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
// 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)
Login to try C/C++/Java/PHP code in the editor
Errors with Associated Values
बिल्कुल किसी और enum की तरह, एक error type associated values रख सकता है यह ज़्यादा detail प्रदान करने के लिए कि क्या गलत हुआ।
उदाहरण: Errors with Associated Values
// 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)
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह भूल जाना कि
throwसे throw किए जाने से पहले एक error type को खालीErrorprotocol conform करना चाहिए। - एक proper enum के बजाय एक plain
Stringया generic type को error के रूप में उपयोग करना जोErrorconform करता है, type-safety और क्या गलत हो सकता है उसकी clarity खोते हुए। - per domain अलग, focused error types के बजाय एक giant enum में कई unrelated error cases define करना।
चैप्टर सारांश
- कोई भी type
Errorprotocol 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: