iT邦幫忙

1

Day 11: 錯誤處理(try-catch)

c#
  • 分享至 

  • xImage
  •  

錯誤處理(Error Handling)
主要是透過try-catch區塊來實現的。這是一種結構化的異常處理機制,用於應對程式運行時可能發生的錯誤,而不是讓程式直接崩潰

為什麼需要錯誤處理?
程式在執行過程中,可能會遇到「例外 (Exception)」情況,例如:
除以零 (DivideByZeroException)
陣列索引超出範圍 (IndexOutOfRangeException)
輸入格式錯誤 (FormatException)
如果沒有處理,程式會「直接中斷」

結構介紹

  1. try
    try 區塊內放置可能拋出異常的程式碼
    程式會嘗試執行這段程式碼

  2. catch
    如果 try 區塊中的程式碼拋出異常,程式會跳到這裡
    您可以在 catch 區塊中指定要捕獲的異常類型(例如 FormatException、DivideByZeroException 等),然後執行處理或記錄錯誤的邏輯

  3. finally
    finally 區塊內的程式碼無論有沒有錯誤都會執行
    它通常用於執行清理工作,例如關閉檔案、釋放資源或關閉資料庫連線

基本語法
https://ithelp.ithome.com.tw/upload/images/20250926/201789258BMe9vJBzK.png

範例
1.
https://ithelp.ithome.com.tw/upload/images/20250926/20178925YFCFAIcpGs.png

  1. 多個catch
    https://ithelp.ithome.com.tw/upload/images/20250926/20178925QN4dG4tfT9.png

  2. finally區塊
    https://ithelp.ithome.com.tw/upload/images/20250926/20178925B9S9MSV4zS.png

https://ithelp.ithome.com.tw/upload/images/20250926/20178925p8okUWsg5R.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言