C# 快速導覽 - throw 陳述

關鍵字 (keyword) throw 用來丟出例外 (exception) ,舉例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Demo {
    static void Main() {
        string s = null;
 
        if (s == null) {
            throw new System.Exception();
        }
 
        System.Console.Write("The string s is null");
    }
}
 
/* 《程式語言教學誌》的範例程式
    檔名:throw1.cs
    功能:示範 C# 程式
    作者:張凱慶
    時間:西元 2013 年 6 月 */


編譯執行,結果如下



此例在第 6 行丟出例外,發生例外就會中止程式執行
6
throw new System.Exception();


因此第 9 行就無法印出
9
System.Console.Write("The string s is null");


如果程式要能處理發生例外後的狀況,而不打斷程式執行,就得加入 try-catch 的例外處理 (exception handling) ,上例修改如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Demo {
    static void Main() {
        string s = null;
         
        try {
            if (s == null) {
                throw new System.Exception();
            }
        }
        catch {
            System.Console.WriteLine("something wrong");
        }
 
        System.Console.WriteLine("The string s is null");
    }
}
 
/* 《程式語言教學誌》的範例程式
    檔名:throw2.cs
    功能:示範 C# 程式
    作者:張凱慶
    時間:西元 2013 年 6 月 */


編譯執行,結果如下



中英文術語對照
關鍵字keyword
例外exception
例外處理exception handling


您可以繼續參考
例外處理


相關目錄
回 C# 快速導覽
回 C# 教材
回首頁


參考資料
Standard ECMA-334 C# Language Specification
msdn: 例外處理陳述式 (C# 參考)

沒有留言: