(Swift) Error handling 簡單介紹

Lin
Lin
Sep 5, 2018 · 2 min read

在做產品開發時,也許你會自己設計某個method,那個method如果出現異常他會拋出拋error出來,這樣拋error出來可以讓我們程式碼架構更乾淨,不必為了這個錯誤原因搞得很亂,這時候就可以用 Error handling

精簡版寫法

如果你不在意原因,我只想知道成功或失敗,如果我失敗我就會在try前面傳回一個nil,所以我就可以用nil或是非nil來判斷成功或失敗

完整版用法

好處是如果我失敗我知道原因是什麼

try! 用法

他的概念是,我把Error handling檢查機制關掉了,就是我不在意成功或失敗

而且我假設一定成功,所以用try!一定要小心,如果這邊失敗了,我們app就會crash

    Lin

    Written by

    Lin

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade