Console.WriteLine(getb(1, 2));
static int getb(int a, int b)
{
try{
b = a + b;
Console.WriteLine(b);
return b;
}
finally{
b = 3 * b;
Console.WriteLine(b);
}
}
官網解釋:
By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block. Typically, the statements of a finally block run when control leaves a try statement. The transfer of control can occur as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.
static int getb(int a, int b)
{
try{
b = a + b;
//直接輸出了這個沒有異議吧?
Console.WriteLine(b);
//return會離開try,因此激活了finally,finally結束前不做return操作,但是return的資料已經堆好了
return b;
}
finally{
b = 3 * b;
//順序執行就輸出了
Console.WriteLine(b);
}
}