C# 入門指南 - 例外處理

資料來源:http://pydoing.blogspot.tw/2012/11/csharp-Exception-Handling.html

 

編譯器 (compiler) 會直接抓語法錯誤 (syntax error) ,可是執行時發生的錯誤會導致程式 (program) 直接結束

c#  

 

encryptgui.cs 完整的範例程式碼,請參考encryptgui.cs



我們替 Encode Decode 設計了防範空字串 (string) 的機制,可是假如使用者沒有先建立 Encrypt 型態 (type) 的屬性 (property) e ,就按下 Encode Decode 的話,就會發生 NullReferenceException 的例外,導致程式直接結束。


C#
的例外處理 (exception handling) 很簡單,就把可能發生例外 (exception) 的程式碼放進 try 的程式區塊 (block) 中,然後處理發生例外後的程式碼放到 catch 的程式區塊內。像是 encodeButton_Click() 就要修改如下

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

privatevoidencodeButton_Click(objectsender, EventArgs e) {

    if(this.inputText == "") {

        this.displayLabel.Text = "This is Encode button. No input string!!";

    }

    else{

        try{

            this.outputText = this.e.toEncode(this.inputText);

            this.outputField.Text = this.outputText;

            this.displayLabel.Text = "This is Encode button. The result is above.";

        }

        catch(NullReferenceException nre) {

            this.displayLabel.Text = "This is Encode button. No Encrypt object!!";

        }

    }

}



try
catch 都是關鍵字 (keyword) 之一, catch 後用小括弧指名要抓取的例外型態,如此例為 NullReferenceException

190

191

192

catch(NullReferenceException nre) {

    this.displayLabel.Text = "This is Encode button. No Encrypt object!!";

}

 

假如同一段程式碼需要處理的例外有多種的話,每一種都需要用 catch 進行處理,因此有可能有多個 catch 陳述。

 

另外還有一個關鍵字 finally ,可放在所有 catch 的最後,這是只要例外發生都會執行的部份。



同樣 decodeButton_Click() 加入 try-catch 如下

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

privatevoiddecodeButton_Click(objectsender, EventArgs e) {

    if(this.inputText == "") {

        this.displayLabel.Text = "This is Decode button. No input string!!";

    }

    else{

        try{

            this.outputText = this.e.toDecode(this.inputText);

            this.outputField.Text = this.outputText;

            this.displayLabel.Text = "This is Decode button. The result is above.";

        }

        catch(NullReferenceException nre) {

            this.displayLabel.Text = "This is Decode button. No Encrypt object!!";

        }

    }

}



再來編譯測試看看囉!輸入 "There is no spoon." ,然後點擊 Encode



做了例外處理,程式就 ok 囉!接下來我們來進行存檔與載入

中英文術語對照

編譯器

compiler

語法錯誤

syntax error

程式

program

字串

string

型態

type

屬性

property

例外處理

exception handling

例外

exception

區塊

block

關鍵字

keyword

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 bike 的頭像
    bike

    abcbike的筆記書摘

    bike 發表在 痞客邦 留言(0) 人氣()