AnyCompiler

Error Handling, Aur Ek Closing Look

Ek function jo fail ho sakta hai usay throws mark kiya jata hai, aur ye Error protocol ko conform karne wali ek value throw karke failure signal karta hai — typically ek enum, jaise neeche. Ek throwing function ko call karne ke liye try chahiye, aur ek do block jiske sath matching catch ho, agar waqai koi error throw ho to usay handle kar leta hai.

enum MathError: Error {
    case divideByZero
}
func safeDivide(_ a: Int, _ b: Int) throws -> Int {
    if b == 0 {
        throw MathError.divideByZero
    }
    return a / b
}
do {
    let result = try safeDivide(10, 0)
    print(result)
} catch {
    print("Caught: \(error)")
}
Output
Caught: divideByZero

Upar wala plain catch kisi bhi Error ko pehle ek named pattern se bind kiye baghair catch kar leta hai, aur error ek implicit naam hai jo Swift us block ke andar provide karta hai — spirit mein Java ke checked exceptions ya Kotlin ke try/catch jaisa, lekin is ke liye function signature par hi, us ke return type ke bilkul sath, throws keyword chahiye hota hai.

Yehi Swift ka foundation hai: optionals jo type system se enforce hote hain runtime par discover hone ke bajaye, structs default value-type choice ke taur par (mutating ke sath ye mark karte hue ke kaunse methods ek change karne ki ijazat rakhte hain), state par react karne ya derive karne ke liye property observers aur computed properties, unrelated types ke liye lightweight shared behavior ke liye protocols, enums jo har case mein real data carry karte hain, aur concise, expressive code likhne ke liye closures aur extensions. Yahan se, best next step practice hai — ek chhota program choose karein aur isay banayein, compiler ki static type checking (aur khaas taur par us ke optionals) par inhisaar karte hue mistakes ko pakarne ke liye jaise aage barhte hain.

Practice exercise

Ek enum MathError: Error define karein jis mein case divideByZero ho. Ek function safeDivide(_ a: Int, _ b: Int) -> Int likhein jo internally do/try/catch istemal kare: jab b 0 ho to ye MathError.divideByZero throw kare (jo catch ho kar 0 return kare), warna a / b return kare. safeDivide(10, 0) print karein.

← GenericsAur lessons jald aa rahe hain