作者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