我們不能期望使用者始終輸入正確的詳細資訊。但是,如果不正確或意外的輸入沒有正確處理,整個程式碼可能會崩潰或陷入無限循環。這是由於意外條件或輸入而在執行程式時出現的問題。例如,當數字除以零時,結果是無限的。異常處理是告訴程式繼續執行下一個程式碼區塊或在某些情況下提供定義的結果的方法。
可以使用以下四個關鍵字來完成異常處理。
透過定義異常處理程序,您可以使軟體或程式碼免於很多麻煩。在可能出現異常的地方定義異常處理程序是一個很好的做法。
文法:
每當引發異常時,宣告的方法都會藉助 try 和 catch 關鍵字捕捉異常。我們需要將此組合放在程式碼部分,預計會出現異常。這些代碼稱為受保護代碼。您也可以為一個 try 關鍵字定義多個 catch 關鍵字。在內容的最後,程式碼的最後部分將被執行到,並且無論是否引發異常都會執行。
代碼:
try { //Define the statement that could cause an exception. } Catch(ExceptionName secondException) { //error handling code } Finally { //define the statement that will be executed }
有許多預先定義的類別用於處理異常。 try 區塊覆蓋了可能引發異常的程式碼部分,而 catch 則確認捕獲異常時要執行的操作。該區塊的最後部分定義了無論是否偵測到異常都必須執行的操作,並且 throw 部分將顯示訊息(如果設定了任何訊息)。
C# 中有很多類別可以用來表示異常。所有類別均衍生自名為 System 的主類別。例外。有幾個類別也是從 System.ApplicationException 和 System.SystemException 衍生出來的。
異常源自 System.異常類別。這是 C# 常見異常類別的列表。
Exception | Description |
System.DivideByZeroException | handles the error when trying to divide a number by zero. |
System.NullReferenceException | handles the error when referring to an object which does not exist. |
System.InvalidCastException | handles the error when trying invalid casting. |
System.IO.IOException | All input-output error is handled. |
System.FieldAccessException | When trying to access unauthorized class |
Exception handling is done by try and catches block in C#. The try block in C# is used to place the code that may throw an exception. The exception is handled by the catch block.
Code:
using System; public class exceptionhandling { public static void Main(string[] args) { int a = 10; int b = 0; int x = a/b; //we are trying to divide the number with zero Console.WriteLine("other part of the code"); } }
Output:
Code
using System; public class ExExample { public static void Main(string[] args) { try { int a = 10; int b = 0; int x = a / b; } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Rest of the code"); } }
Output:
It will show you the message regardless the exception is caught.
Code
using System; public class Exceptionhandling { public static void Main(string[] args) { try { int x = 5; int y= 0; int z = x / y; } catch (Exception obj) { Console.WriteLine(obj); } finally { Console.WriteLine("Time to execute finally block"); } Console.WriteLine("Other part of the code"); } }
Output:
Code
using System; public class ExceptionHandling { public static void Main(string[] args) { try { int p = 6; int q = 0; int r= p/q; } catch (NullReferenceException nullObject) { Console.WriteLine(nullObject); } finally { Console.WriteLine("Exception not handled. Now Finally section will be executed"); } Console.WriteLine("Other part of the code"); } }
Output:
The not only system defined, but we can also set our own exception. However, we need to inherit the code in order to get this done.
Code
using System; public class userdefinedInvalidAge : Exception { public userdefinedInvalidAge (String errorMessage) : base(errorMessage) { } } public class TestUserDefinedException { static void validateAge(int age) { if (age < 18) { throw new userdefinedInvalidAge("Sorry, Age must be greater than 18"); } } public static void Main(string[] args) { try { validateAge(12); } catch (userdefinedInvalidAge e) { Console.WriteLine(e); } Console.WriteLine("Rest of the code"); } }
Output:
At any place you think it might generate an error because of anything, exception handler should be used. It is essential that you use a catch statement and start from generic to a specific exception. Your entire software or code is at risk without proper exception handler.
以上是C# 中的例外處理的詳細內容。更多資訊請關注PHP中文網其他相關文章!