C++ exception

今天看书发现抛出异常,有几种不同的写法,查找资料找出了不同之处。

C++对异常对象的传递有按值传递、按引用传递和按指针传递三种方式。

上表格:

throw 方式的不同导致catch 时形参类型不同。

参考:

http://www.parashift.com/c++-faq-lite/what-to-catch.html

http://www.parashift.com/c++-faq-lite/catch-by-ptr-in-mfc.html

In fact, you have all the flexibility that you have in declaring function parameters, and the rules for whether a particular exception matches (i.e., will be caught by) a particular catch clause are almost exactly the same as the rules for parameter compatibility when calling a function.

Given all this flexibility, how do you decide what to catch? Simple: unless there's a good reason not to, catch by reference. Avoid catching by value, since that causes a copy to be made and the copy can have different behavior from what was thrown. Only under very special circumstances should you catch by pointer.

通常,如果没有特殊原因,通过引用传递;避免传值,因为按值传递会引发拷贝,而此拷贝可能会和原来抛出的异常不同;只有在特殊情况下才使用指针传递。

对于自带的exception和自己写的exception的比较:

Depends. If you're using MFC and catching one of their exceptions, by all means, do it their way. Same goes for any framework: when in Rome, do as the Romans. Don't try to force a framework into your way of thinking, even if "your" way of thinking is "better." If you decide to use a framework, embrace its way of thinking — use the idioms that its authors expected you to use.

如果在使用MFC时,使用自带的exception,不要用自己的exception。

But if you're creating your own framework and/or a piece of the system that does not directly depend on MFC, then don't catch by pointer just because MFC does it that way. When you're not in Rome, you don't necessarily do as the Romans. In this case, you should not. Libraries like MFC predated the standardization of exception handling in the C++ language, and some of these libraries use a backwards-compatible form of exception handling that requires (or at least encourages) you to catch by pointer.

当自己写架构时,系统的一部分不依赖于MFC,不要像MFC那样按指针传递。

像MFC等库出现早于C++标准异常处理,一些库都采用向下兼容的异常处理方式,需要(至少鼓励)你按指针传递。

按指针传递会有上述表格中的问题。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值