C# 內建異常
異常是在程式執行時出現的某個問題。以下關鍵字處理 C# 中的異常
try
try 塊標識一個程式碼塊,用於啟用特定異常。
Catch
catch 關鍵字表示捕獲異常。
finally
執行給定的語句集,無論是否丟擲異常。
throw
當程式中出現問題時丟擲一個異常。
示例
讓我們看一個示例來處理 C# 程式中的錯誤
using System; namespace MyErrorHandlingApplication { class DivNumbers { int result; DivNumbers() { result = 0; } public void myDivision(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception Caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.myDivision(5, 0); Console.ReadKey(); } } }
輸出
Result: 0
廣告