我有興趣進一步了解以下代碼邏輯的行為方式:
try
{
// might, or might not do this: throw ExceptionTypeA;
function_which_might_throw_exception_type_a();
do_A(); // do we do A?
}
catch(ExceptionTypeB)
{
// B will never be done
do_not_do_B();
}
// C is always done (Edit: should always be done, but actually isn't)
do_C();
簡而言之,這個問題可以簡單地表述為:函式do_A會被呼叫嗎?*
*[If function_which_might_throw_exception_type_a()does throw ExceptionTypeA;...當然很清楚,如果不拋出例外do_A() 就會被呼叫。]function_which_might_throw_exception_type_a()
catch上面的偽代碼應該表達拋出一個與子句中捕獲的例外型別不同的型別的例外。
換句話說,雖然有catch子句,但這里不會捕獲例外,因為它的型別不正確。
在這種情況下,編譯器是否會產生一個完全跳過呼叫的do_A()輸出,或者編譯器是否會產生一個輸出,其中do_A()被稱為`?
我相當有信心,如果在 try 塊中拋出任何例外,那么執行路徑是立即離開 try 塊。換句話說,我認為do_A()上面的偽代碼中沒有呼叫。(假設函式function_which_might_throw_exception_type_a()確實 throw ExceptionTypeA。)
但是我想檢查一下,因為我開始懷疑。
僅供參考:我正在看一段代碼,它更明智地寫成:
try
{
// might, or might not do this: throw ExceptionTypeA;
function_which_might_throw_exception_type_a();
do_A(); // do we do A?
// C **should** always be done
do_C()
}
catch(ExceptionTypeB)
{
// B will never be done
do_not_do_B();
}
return something;
但是,我認為這不等同于第一個偽代碼。
由于 C 沒有 try-catch-finally 型別的陳述句,所以無法用這種方式表達邏輯。(但我認為如果可以的話會更好。)
uj5u.com熱心網友回復:
會呼叫函式 do_A 嗎?
簡而言之——不。當塊內拋出例外時try,該塊將立即退出。如果拋出的例外型別沒有由相應的catch塊處理,那么它將被視為在try塊外拋出的例外(可能導致堆疊展開,但最終導致程式終止)。
如果您希望您的do_C()函式被稱為“始終”,無論拋出什么型別的例外,那么您應該catch(...)在您的其他特定塊之后添加一個(稱為“catch-all 子句”)塊catch。這可以是一個空陳述句/塊;如果是這樣,拋出的例外仍然被捕獲(即不會進一步傳播)但不采取特定的行動。
實作您似乎想要的一種可能的方法如下:
try
{
// might, or might not do this: throw ExceptionTypeA;
function_which_might_throw_exception_type_a();
do_A(); // If the above throws, this WILL NOT be executed
}
catch(ExceptionTypeB)
{
// B will never be done
do_not_do_B();
}
catch(...) {} // This will catch "ExceptionTypeA" but do nothing about it ...
do_C(); // Will 'always' execute (unless an earlier catch re-throws)
return something;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454114.html
