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

来源:互联网 发布:mac奶瓶粉底液价格 编辑:程序博客网 时间:2024/06/05 14:36

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);
            }