Error Handling, Aur Ek Closing Look
Ek function jo fail ho sakta hai use throws mark kiya jaata 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 saath matching catch ho, agar actually koi error throw ho to use 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)")
}Caught: divideByZero
Upar wala plain catch kisi bhi Error ko pehle ek named pattern se bind kiye bina 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 iske liye function signature par hi, uske return type ke bilkul saath, throws keyword chahiye hota hai.
Yahi 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 saath ye mark karte hue ki kaunse methods ek change karne ki permission rakhte hain), state par react karne ya derive karne ke liye property observers aur computed properties, unrelated types ke across 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 karo aur use banao, compiler ki static type checking (aur khaaske uske optionals) par relying karte hue mistakes ko pakadne ke liye jaise aage badhte ho.
Practice exercise
Ek enum MathError: Error define karo jisme case divideByZero ho. Ek function safeDivide(_ a: Int, _ b: Int) -> Int likho jo internally do/try/catch use 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 karo.