如果代碼即試圖訪問該文件位於前端,例如用於點擊的事件處理程序,則可以檢查錯誤情況,顯示消息並返回。
如果我正確理解你的問題,你想知道你是否應該這樣做:
public void button_Click() {
if(!File.Exists(textBox.Text)) {
MessageBox.Show("Could not find the file");
return;
}
ProcessFile(textBox.Text); // would have thrown an exception if the file didn't exist
}
這將是罰款,除非ProcessFile拋出任何其他類型的異常也不會被處理。
你可以這樣做:
public void button_Click() {
try {
ProcessFile(textBox.Text); // throwns an exception if the file didn't exist
} catch(Exception ex) {
MessageBox.Show(GetUserMessage(ex));
return;
}
}
在我看來這是更好地做到既:
public void button_Click() {
try {
if(!File.Exists(textBox.Text)) {
MessageBox.Show("Could not find the file");
return;
}
ProcessFile(textBox.Text); // throwns an exception if the file didn't exist
} catch(Exception ex) {
MessageBox.Show(GetUserMessage(ex));
return;
}
}
這種方式可以提供最具體的消息,與用戶相關的他在做什麼在此刻。例如,如果他試圖打開Excel文件,可以說「找不到想要導入的Excel文件」。
這也適用於在您檢查的點與您嘗試處理文件的位置之間刪除或重命名文件的情況。
另外,您可以完成此類似:
public void button_Click() {
try {
if(!File.Exists(textBox.Text)) {
throw new UserException("Could not find the file");
}
ProcessFile(textBox.Text); // throwns an exception if the file didn't exist
} catch(Exception ex) {
MessageBox.Show(GetUserMessage(ex));
return;
}
}
在這種情況下,你會創建自己的Exception類UserException
,只是沿着傳遞消息,而無需轉換它。這將允許您重複使用您用來顯示消息的相同代碼。
例外類
如果在一些類庫時出現錯誤,那麼你應該拋出異常。例外的目的是不能忽視錯誤。
例如,你不應該這樣想:
class MyFileHandler {
public void OpenFile(string fileName) {
if(!File.Exists(fileName)) return;
// do stuff
}
public void DoStuff() {
// do stuff
}
}
現在,如果一個開發者稱爲myFileHandlerInstance.OpenFile("note.txt")
,他會認爲它的工作。你可以返回一個布爾值,像這樣:
class MyFileHandler {
public bool OpenFile(string fileName) {
if(!File.Exists(fileName)) return false;
// do stuff
return true;
}
public void DoStuff() {
// do stuff
}
}
但現在你是依靠開發者檢查值,這曾經是一個常用的方法,但誤差得到了忽略,忽視這就是爲什麼例外成爲更好的做法。至於要顯示給用戶的內容,你實際上不應該直接顯示異常消息,這些消息是針對開發者而不是用戶的。我建議採取一個異常對象,並返回最佳的消息,像這樣的方法:
public string GetUserErrorMessage(Exception ex) {
if(ex is FileLoadException) {
var fileLoadException = (FileLoadException)ex;
return "Sorry but we failed to load the file: " + fileLoadException.FileName;
}
}
您可以檢查異常屬性的細節,包括錯誤代碼,如果你喜歡。此外,我建議在某處爲您自己的調試目的捕獲實際的異常詳細信息,這些地方對用戶不可見。
這是一個*真的*不好主意。你已經得到一個體面的異常消息,沒有這個代碼。只需捕捉StreamReader構造函數拋出並顯示其Message屬性的異常即可。 –
是的,我明白,但我想展示一個用戶可以輕鬆理解的自定義消息,避免異常而不是更好地抓住它? – CudoX
您應該將消息呈現與io訪問分開。也許你的代碼有一天會在控制檯應用程序中使用?順便說一句,只使用意外的執行路徑的異常,而不是像不存在的文件。 –