C++中的异常问题的总结

Linux 下 C++ 异常处理技巧

http://www.ibm.com/developerworks/cn/linux/l-cppexcep.html



C++中异常处理的语法 try catch throw

http://www.cnblogs.com/8586/archive/2009/05/28/1491288.html

给出了异常的基本用法,以及多个异常(用于异常分类)和嵌套异常、



注意在catch中不能使用 string&等:

http://stackoverflow.com/questions/134569/c-exception-throwing-stdstring


You need to catch it with char const* instead of char*. Neither anything like std::string norchar* will catch it.

Catching has restricted rules with regard to what types it match. The spec says (where "cv" means "const/volatile combination" or neither of them).

A handler is a match for an exception object of type E if

  • The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
  • the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or
  • the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of

    • a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes
    • a qualification conversion

A string literal has type char const[N], but throwing an array will decay the array and actually throws a pointer to its first element. So you cannot catch a thrown string literal by a char*, because at the time it matches, it needs to match the char* to a char const*, which would throw away a const (a qualification conversion is only allowed to add const). The special conversion of a string literal to char* is only considered when you need to convert a string literal specifically.

如果一定想用string,那最好出去后再转。如下例:

try {
                if (left_brackets_stack.empty()) {
                    throw "nomatched_left_brackets";
                }
                std::string pair_left = left_brackets_stack.top();
                left_brackets_stack.pop();
                std::pair<std::string, std::string> pair(pair_left, myitoa(position));
                return_value->push_back(pair);
            }catch(const char* empty_exception){
                std::string str_empty_exception(empty_exception);
                std::pair<std::string, std::string> pair(str_empty_exception,BracketsChecker::myitoa(position));
                return_value->push_back(pair);
            }  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值