【发布时间】:2017-09-25 05:28:53
【问题描述】:
我一年多来的实践是为我正在编写的每个方法提供一个单独的 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 的 Main 方法会更好吗?
谢谢
【问题讨论】:
-
这取决于你想如何处理你的异常。
-
在你的例子中,你只能使用
MainMethod的块。 -
根据我的观点,我只会在
MainMethod()中使用try/catch。 -
我建议在你的 main 方法上设置一个 try catch 块,但是我建议你把你的逻辑放到 try catch 并等待异常引发。检查空对象或在转换时尝试强制转换等可以有效地使用。
-
只有在子方法执行某种算术或次要过程时才会这样,对吗?如果他们正在访问数据访问层并就使用数据库事务而言,那嵌套的
try/catch块将受益,对吧?我的意思是,回滚交易必须在 Catch Block 上进行。
标签: c# methods nested try-catch