C# 中的例外處理

WBOY
發布: 2024-09-03 15:20:23
原創
953 人瀏覽過

我們不能期望使用者始終輸入正確的詳細資訊。但是,如果不正確或意外的輸入沒有正確處理,整個程式碼可能會崩潰或陷入無限循環。這是由於意外條件或輸入而在執行程式時出現的問題。例如,當數字除以零時,結果是無限的。異常處理是告訴程式繼續執行下一個程式碼區塊或在某些情況下提供定義的結果的方法。

C# 中異常處理的關鍵字

可以使用以下四個關鍵字來完成異常處理。

  1. Try: try 區塊定義要處理的異常類型。這是捕獲異常的地方。它總是與一個 catch 區塊配對。
  2. Catch: 一旦 try 區塊定義了類型並在執行過程中得到一個異常,catch 區塊將確認要使用的異常處理程序的類型。該區塊還將確定在何處處理異常。正如關鍵字所示,這就像捕獲異常。
  3. 最後: 該區塊有一些語句集。無論拋出異常,最終區塊中定義的語句都將始終被執行。
  4. Throw:當捕獲到異常時,使用 throw 關鍵字來顯示捕獲到的異常。

透過定義異常處理程序,您可以使軟體或程式碼免於很多麻煩。在可能出現異常的地方定義異常處理程序是一個很好的做法。

文法:

每當引發異常時,宣告的方法都會藉助 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
}
登入後複製

C# 中的異常處理如何運作?

有許多預先定義的類別用於處理異常。 try 區塊覆蓋了可能引發異常的程式碼部分,而 catch 則確認捕獲異常時要執行的操作。該區塊的最後部分定義了無論是否偵測到異常都必須執行的操作,並且 throw 部分將顯示訊息(如果設定了任何訊息)。

C# 中的異常類別

C# 中有很多類別可以用來表示異常。所有類別均衍生自名為 System 的主類別。例外。有幾個類別也是從 System.ApplicationException 和 System.SystemException 衍生出來的。

C# 中的異常類別範例

異常源自 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
                   異常                    說明 System.DivideByZeroException 處理嘗試將數字除以零時的錯誤。 System.NullReferenceException 處理引用不存在的物件時的錯誤。 System.InvalidCastException 處理嘗試無效轉換時的錯誤。 System.IO.IOException 所有輸入輸出錯誤均已處理。 System.FieldAccessException 嘗試存取未經授權的類別時 表>

1. C# try/catch

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.

C# example without try/catch

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:
C# 中的例外處理

C# try/catch example

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:
C# 中的例外處理

Use of Exception Classes in C# finally

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:
C# 中的例外處理

1. C# finally example if Exception is not handled

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:
C# 中的例外處理

2. C# user-defined Exception

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:
C# 中的例外處理

Conclusion

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中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!