IF語句我有類似下面的方法:最佳實踐與Catch塊
public static addSomething(int id)
{
string msg = getStringMsg(id);
try
{
//do lots of stuff
Console.WriteLine(msg)
}
catch (Exception e)
{
if (id == 1)
throw new Exception("Exception msg 1: " + msg);
else
throw new Exception("Exception msg 2: " + msg);
}
}
是具有令人難以接受的catch塊這樣的條件分支?如果是這樣,我的替代品是什麼?
我想我可以這樣做:
public static addSomething(int id)
{
string msg = getStringMsg(id);
string exceptionMsg;
if (id == 1)
exceptionMsg = "Exception msg 1: " + msg);
else
exceptionMsg = "Exception msg 2: " + msg);
try
{
//do lots of stuff
Console.WriteLine(msg)
}
catch (Exception e)
{
throw new Exception(exceptionMsg);
}
}
但我真的想保持代碼的try塊外面到最低限度,如果在所有。關於我的第二個問題:是否有一種方法可以在try
塊內將getStringMsg(id)
分配給msg
,但仍然可以在catch
塊中訪問它?
對於代碼的可讀性,我會親自去你的第一個例子。我的問題是爲什麼你不會僅僅採用e.Message,msg和id,將其格式化爲您的需要,然後將其泡大。一般來說catch塊是爲了恢復應用程序,而不是用於業務邏輯。 – AWinkle
還有一個問題 - 你是否真的需要將'getStringMsg(id)'返回的'msg'添加到錯誤信息中?你需要什麼東西*部分 - 'msg'或'id',或者他們兩個? –
對第一個問題的回答是肯定的。這是一個非常簡化的版本,可以解決問題的核心問題。是的,我需要在'//很多東西'中使用'msg'和'id'。 – dursk