Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Error Handling

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

App တစ်ခုမှာ file မတွေ့တာ၊ network failed ဖြစ်တာ၊ payment မအောင်မြင်တာ၊ input မမှန်တာလို runtime issue တွေဖြစ်နိုင်ပါတယ်။ Swift မှာ throw, throws, do-catch, try တွေနဲ့ error ကိုစနစ်တကျကိုင်တွယ်နိုင်ပါတယ်။

swift
enum LoginError: Error {
    case emptyUsername
    case wrongPassword
}

func login(username: String, password: String) throws {
    if username.isEmpty {
        throw LoginError.emptyUsername
    }

    if password != "123456" {
        throw LoginError.wrongPassword
    }

    print("Login success")
}

do {
    try login(username: "sai", password: "wrong")
} catch LoginError.emptyUsername {
    print("Username is required")
} catch LoginError.wrongPassword {
    print("Password is incorrect")
} catch {
    print("Something went wrong")
}

login function က error ဖြစ်နိုင်လို့ throws ထည့်ထားပါတယ်။ Function ကိုခေါ်တဲ့အခါ try လိုပြီး error ဖြစ်ရင် catch block တစ်ခုခုထဲဝင်ပါတယ်။

You should see
Password is incorrect

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • try လိုတဲ့ function ကို do-catch မပါဘဲခေါ်ရင် compile error ဖြစ်နိုင်ပါတယ်။
Error Handling | Thuta Learning