
encryptgui.cs 完整的範例程式碼,請參考encryptgui.cs
我們替 Encode 與 Decode 設計了防範空字串 (string) 的機制,可是假如使用者沒有先建立 Encrypt 型態 (type) 的屬性 (property) e ,就按下 Encode 或 Decode 的話,就會發生 NullReferenceException 的例外,導致程式直接結束。
C# 的例外處理 (exception handling) 很簡單,就把可能發生例外 (exception) 的程式碼放進 try 的程式區塊 (block) 中,然後處理發生例外後的程式碼放到 catch 的程式區塊內。像是 encodeButton_Click() 就要修改如下
private void encodeButton_Click(object sender, 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
catch (NullReferenceException nre) {
this.displayLabel.Text = "This is Encode button. No Encrypt object!!";
}假如同一段程式碼需要處理的例外有多種的話,每一種都需要用 catch 進行處理,因此有可能有多個 catch 陳述。
另外還有一個關鍵字 finally ,可放在所有 catch 的最後,這是只要例外發生都會執行的部份。
同樣 decodeButton_Click() 加入 try-catch 如下
private void decodeButton_Click(object sender, 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 |
您可以繼續參考
GUI 篇
相關目錄
回 C# 入門指南
回 C# 教材
回首頁
參考資料
http://msdn.microsoft.com/zh-tw/library/0yd65esw%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/zwc8s4fz%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/dszsf989%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/ms173160%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/ms173161%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/ms173162%28v=vs.80%29.aspx
沒有留言:
張貼留言