作者ric2k1 (Ric)
看板EE_DSnP
標題Re: [問題] throw和catch
時間Wed May 6 20:53:24 2009
※ 引述《jokerspy (蘇哥)》之銘言:
: 不太清楚throw和catch的功用耶
: 假如throw都是要經過if判斷來決定要不要throw
: 那為何要另外丟throw再由catch去接然後執行
: 直接用if做判斷然後執行不就可以了??
理論上是的, 但是 throw 所發生的情況是表示有 exception,
試想, 在你的 getMem(t) 裏面遇到:
if (t > _blockSize)
這種情況, 你如果不用 throw 的, 你就得 return T*,
那你要 return 什麼呢?
就算 return 回去了, 上一層 (或兩層) 的 caller function(s)
"alloc(t)", "new (t)" 要特別去 handle 嗎?
所以既然是 exception, 就乾脆用 throw 的, 然後只要上面 (衝出 main() 之前)_
有人 catch 就好了...
: 又如果只有throw但是沒有catch是不是不行阿?
: 我現在只有throw沒有catch compile就會
: terminate called after throwing an instance of'std::badalloc'
: what( ) : St9bad_alloc
沒錯, throw 了沒有 catch 而跑出 main() 之外就會 crash!
: 但是有人就不會耶
: 所以到底是要滿足甚麼樣的格式?
不會吧, 他可能暗嵌他的 code 不給你看... XD
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.224.45.41
1F:推 jokerspy:那這次的case catch到bad_alloc之後要做甚麼呢? 05/06 21:05
2F:推 Ultor:所以是不是如果在一個function裡面throw之後 05/06 21:16
3F:→ Ultor:在被catch到之前 這段中間的程式碼都不會被執行呢 05/06 21:16
4F:→ ric2k1:To 1F, 請看作業說明 05/06 21:50
5F:→ ric2k1:To 2F, yes. 05/06 21:50