我現在的做法已經超過一年了,現在是爲每個我正在編寫的方法提供一個單獨的try/catch塊,然後在特定的代碼塊失敗時拋出異常對象。例如:我應該在每種方法上提供try/catch,還是隻提供主要方法?
void MainMethod()
{
try {
int num = Method1();
string str = Method3();
bool bln = Metho4();
} catch (Exception Ex) {
MessageBox.Show(Ex.Message);
}
}
int Method1() {
try {
return 123 + Method2();
} catch (Exception) {
throw;
}
}
int Method2() {
try {
return Convert.ToInt32("One Hundred"); // <-- Obviously would fail.
} catch (Exception) {
throw;
}
}
string Method3() {
try {
string str1 = "Hello ";
return str1 + 12345; // <-- Would also fail.
} catch(Exception) {
throw;
}
}
bool Method4() {
try {
return true;
} catch(Exception) {
throw;
}
}
我應該爲每個方法提供他們自己/單獨的try/catch塊嗎?或者,如果它的主要方法有try/catch,會更好嗎?
謝謝
這取決於你想如何處理你的例外。 – SeM
就你的例子而言,你只能使用'MainMethod'塊。 – SeM
根據我的觀點,我會在'MainMethod()'中只使用'try/catch'。 – mmushtaq