以前用過一段時間Python,里面有個try/catch/else語法,我覺得挺好用,這個語法形如下:
try:
print('try...')
r = 10 / int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
這段代碼來至廖雪峰的教程,我覺得這個語法挺好的,我舉一個C#的例子:
static void Main(string[] args)
{
int result = 0;
bool hasEx = false;
try
{
result = Div(100, 1);
}
catch (Exception ex)
{
Console.WriteLine("it's wrong:" + ex.Message);
hasEx = true;
}
if (!hasEx)
{
DoSomthing(result);
}
Console.ReadLine();
}
static int Div(int dividend, int divider)
{
return dividend / divider;
}
static void DoSomething(int result)
{
Console.WriteLine("do somthing with " + result);
}
上例中,我想在調用Div方法沒有拋出異常的情況下才執行DoSomething方法,一般的處理方法如上面代碼所示,用一個bool型變量來判斷是否超出了異常,這樣寫出的代碼並不是很優雅。也許有人會說把DoSomething方法放到Div方法的下面,如果Div方法拋出了異常的話就不會執行DoSomething方法了,但是這樣做有一個問題:一個try塊中放置多個可能拋出異常的方法本身不太合理,一旦catch到異常,可能需要額外的設計才能使得catch中的代碼知道異常到底是Div方法拋出的還是DoSomething拋出的。基於如上考慮,我寫了一個輔助類:
public static class TryCatchElseHelper
{
public static void Do<TResult>(Func<TResult> tryToDo,
Action<Exception> catchTodo,
Action<TResult> elseTodo)
{
bool catchEx = false;
TResult result = default(TResult);
try
{
if (tryToDo != null)
{
result = tryToDo();
}
}
catch (Exception ex)
{
catchEx = true;
catchTodo?.Invoke(ex);
}
if (!catchEx)
{
elseTodo?.Invoke(result);
}
}
}
調用此類,上面Main函數里的代碼可簡化如下:
static void Main(string[] args)
{
TryCatchElseHelper.Do<int>(() => Div(100, 0),
ex => Console.WriteLine("it's wrong " + ex.Message),
r => DoSomething(r));
Console.ReadLine();
}
以上代碼本屬雕蟲小技,大家可以借此來討論討論微軟是否有必要在C#將來的版本中加入try/catch/else的語法,謝謝,祝節日愉快。