# C# 異常處理
異常是在程序執行期間出現的問題。C# 中的異常是對程序運行時出現的特殊情況的一種響應,比如嘗試除以零。
異常提供了一種把程序控制權從某個部分轉移到另一個部分的方式。C# 異常處理時建立在四個關鍵詞之上的:**try**、**catch**、**finally** 和 **throw**。
* **try**:一個 try 塊標識了一個將被激活的特定的異常的代碼塊。后跟一個或多個 catch 塊。
* **catch**:程序通過異常處理程序捕獲異常。catch 關鍵字表示異常的捕獲。
* **finally**:finally 塊用于執行給定的語句,不管異常是否被拋出都會執行。例如,如果您打開一個文件,不管是否出現異常文件都要被關閉。
* **throw**:當問題出現時,程序拋出一個異常。使用 throw 關鍵字來完成。
## 語法
假設一個塊將出現異常,一個方法使用 try 和 catch 關鍵字捕獲異常。try/catch 塊內的代碼為受保護的代碼,使用 try/catch 語法如下所示:
```
try
{
// 引起異常的語句
}
catch( ExceptionName e1 )
{
// 錯誤處理代碼
}
catch( ExceptionName e2 )
{
// 錯誤處理代碼
}
catch( ExceptionName eN )
{
// 錯誤處理代碼
}
finally
{
// 要執行的語句
}
```
您可以列出多個 catch 語句捕獲不同類型的異常,以防 try 塊在不同的情況下生成多個異常。
## C# 中的異常類
C# 異常是使用類來表示的。C# 中的異常類主要是直接或間接地派生于 **System.Exception** 類。**System.ApplicationException** 和 **System.SystemException** 類是派生于 System.Exception 類的異常類。
**System.ApplicationException** 類支持由應用程序生成的異常。所以程序員定義的異常都應派生自該類。
**System.SystemException** 類是所有預定義的系統異常的基類。
下表列出了一些派生自 Sytem.SystemException 類的預定義的異常類:
| 異常類 | 描述 |
| --- | --- |
| System.IO.IOException | 處理 I/O 錯誤。 |
| System.IndexOutOfRangeException | 處理當方法指向超出范圍的數組索引時生成的錯誤。 |
| System.ArrayTypeMismatchException | 處理當數組類型不匹配時生成的錯誤。 |
| System.NullReferenceException | 處理當依從一個空對象時生成的錯誤。 |
| System.DivideByZeroException | 處理當除以零時生成的錯誤。 |
| System.InvalidCastException | 處理在類型轉換期間生成的錯誤。 |
| System.OutOfMemoryException | 處理空閑內存不足生成的錯誤。 |
| System.StackOverflowException | 處理棧溢出生成的錯誤。 |
## 異常處理
C# 以 try 和 catch 塊的形式提供了一種結構化的異常處理方案。使用這些塊,把核心程序語句與錯誤處理語句分離開。
這些錯誤處理塊是使用 **try**、**catch** 和 **finally** 關鍵字實現的。下面是一個當除以零時拋出異常的實例:
```
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(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.division(25, 0);
Console.ReadKey();
}
}
}
```
當上面的代碼被編譯和執行時,它會產生下列結果:
```
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
```
## 創建用戶自定義異常
您也可以定義自己的異常。用戶自定義的異常類是派生自 **ApplicationException** 類。下面的實例演示了這點:
```
using System;
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
```
當上面的代碼被編譯和執行時,它會產生下列結果:
```
TempIsZeroException: Zero Temperature found
```
## 拋出對象
如果異常是直接或間接派生自 **System.Exception** 類,您可以拋出一個對象。您可以在 catch 塊中使用 throw 語句來拋出當前的對象,如下所示:
```
Catch(Exception e)
{
...
Throw e
}
```
- C# 基礎
- C# 簡介
- C# 環境
- C# 程序結構
- C# 基本語法
- C# 數據類型
- C# 類型轉換
- C# 變量
- C# 常量
- C# 運算符
- C# 判斷
- C# 循環
- C# 封裝
- C# 方法
- C# 可空類型(Nullable)
- C# 數組(Array)
- C# 字符串(String)
- C# 結構(Struct)
- C# 枚舉(Enum)
- C# 類(Class)
- C# 繼承
- C# 多態性
- C# 運算符重載
- C# 接口(Interface)
- C# 命名空間(Namespace)
- C# 預處理器指令
- C# 正則表達式
- C# 異常處理
- C# 文件的輸入與輸出
- C# 高級
- C# 特性(Attribute)
- C# 反射(Reflection)
- C# 屬性(Property)
- C# 索引器(Indexer)
- C# 委托(Delegate)
- C# 事件(Event)
- C# 集合(Collection)
- C# 泛型(Generic)
- C# 匿名方法
- C# 不安全代碼
- C# 多線程
- ASP.NET 簡介
- Web Pages 教程
- ASP.NET Web Pages - 教程
- ASP.NET Web Pages - 添加 Razor 代碼
- ASP.NET Web Pages - 頁面布局
- ASP.NET Web Pages - 文件夾
- ASP.NET Web Pages - 全局頁面
- ASP.NET Web Pages - HTML 表單
- ASP.NET Web Pages - 對象
- ASP.NET Web Pages - 文件
- ASP.NET Web Pages - 幫助器
- ASP.NET Web Pages - WebGrid 幫助器
- ASP.NET Web Pages - Chart 幫助器
- ASP.NET Web Pages - WebMail 幫助器
- ASP.NET Web Pages - PHP
- ASP.NET Web Pages - 發布網站
- Razor 教程
- ASP.NET Razor - 標記
- ASP.NET Razor - C# 和 VB 代碼語法
- ASP.NET Razor - C# 變量
- ASP.NET Razor - C# 循環和數組
- ASP.NET Razor - C# 邏輯條件
- ASP.NET Razor - VB 變量
- ASP.NET Razor - VB 循環和數組
- ASP.NET Razor - VB 邏輯條件
- MVC 教程
- ASP.NET MVC 教程
- ASP.NET MVC - Internet 應用程序
- ASP.NET MVC - 應用程序文件夾
- ASP.NET MVC - 樣式和布局
- ASP.NET MVC - 控制器
- ASP.NET MVC - 視圖
- ASP.NET MVC - SQL 數據庫
- ASP.NET MVC - 模型
- ASP.NET MVC - 安全
- ASP.NET MVC - HTML 幫助器
- ASP.NET MVC - 發布網站
- Web Forms 教程
- ASP.NET Web Forms - 教程
- ASP.NET Web Forms - HTML 頁面
- ASP.NET Web Forms - 服務器控件
- ASP.NET Web Forms - 事件
- ASP.NET Web Forms - HTML 表單
- ASP.NET Web Forms - 維持 ViewState
- ASP.NET Web Forms - TextBox 控件
- ASP.NET Web Forms - Button 控件
- ASP.NET Web Forms - 數據綁定
- ASP.NET Web Forms - ArrayList 對象
- ASP.NET Web Forms - Hashtable 對象
- ASP.NET Web Forms - SortedList 對象
- ASP.NET Web Forms - XML 文件
- ASP.NET Web Forms - Repeater 控件
- ASP.NET Web Forms - DataList 控件
- ASP.NET Web Forms - 數據庫連接
- ASP.NET Web Forms - 母版頁
- ASP.NET Web Forms - 導航
- Web Pages 參考手冊
- ASP.NET Web Pages - 類
- ASP.NET Web Pages - WebSecurity 對象
- ASP.NET Web Pages - Database 對象
- ASP.NET Web Pages - WebMail 對象
- ASP.NET Web Pages - 更多幫助器
- MVC - 參考手冊
- Web Forms 參考手冊
- ASP.NET Web Forms - HTML 服務器控件
- ASP.NET Web Forms - Web 服務器控件
- ASP.NET Web Forms - Validation 服務器控件
- 免責聲明