C++ Exception

本文深入解析了C++语言中用于语言支持的异常类,包括bad_alloc、bad_cast、bad_typeid、bad_exception等类,以及标准库提供的异常类如logic_error、range_error、overflow_error等。同时,阐述了标准库自身可能抛出的异常,如range_error、out_of_range和invalid_argument,并解释了如何通过exception类和bad_exception类进行异常捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Exception Classes for Language Support

Exceptions for language support are used by language features. So in a way they are part of the core language rather than the library. These exceptions are thrown when the following operations fail.

• An exception of class bad_alloc is thrown whenever the global operator new fails (except when the nothrow version of new is used). This is probably the most important
exception because it might occur at any time in any nontrivial program.
• An exception of class bad_cast is thrown by the dynamic_cast operator if a type conversion on a reference fails at runtime.
• An exception of class bad_typeid is thrown by the typeid operator for runtime type identification. If the argument to typeid is zero or the null pointer, this exception gets
thrown.
• An exception of class bad_exception is used to handle unexpected exceptions. It does this by using the function unexpected(). unexpected() is called if a function throws

an exception that is not listed in an exception specification (exception specifications). For example:

class El;
class E2;
void f() throw(E1) //throws only exceptions of type E1
{
...
throw El(); //throws exception of type El

...
throw E2();//calls unexpected(), which calls terminate()
}

The throw of an exception of type E2 in f() violates the exception specification. In this case, the global function unexpected() gets called, which usually calls terminate()

to terminate the program. However, if class bad_exception is part of the exception specification, then unexpected() usually rethrows an exception of this type:

class El;
class E2;
void f() throw(E1, std::bad_exception)
//throws exception of type El or
//bad_exception for any other exception type
{
...
throw El(); //throws exception of type El
...
throw E2(); //calls unexpected(), which throws bad_exception
}

Thus, if an exception specification includes the class bad_exception, then any exception not part of the specification may be replaced by bad_exception within the function
unexpected().


Exception Classes for the Standard Library
Exception classes for the C++ standard library are usually derived from class logic_error. Logic errors are errors that, at least in theory, could be avoided by the program; for example, by  performing additional tests of function arguments. Examples of such errors are a violation of logical preconditions or a class invariant. The C++ standard library provides the following classes for logic errors:
• An exception of class invalid_argument is used to report invalid arguments, such as when a bitset (array of bits) is initialized with a char other than '0' or '1'.
• An exception of class length_error is used to report an attempt to do something that exceeds a maximum allowable size, such as appending too many characters to a string.
• An exception of class out_of_range is used to report that an argument value is not in the expected range, such as when a wrong index is used in an array-like collection or string.
• An exception of class domain_error is used to report a domain error. In addition, for the I/O part of the library, a special exception class called ios_base::failure is  provided. It may be thrown when a stream changes its state due to an error or end-of-file.


Exception Classes for Errors Outside the Scope of a Program

Exceptions derived from runtime_error are provided to report events that are beyond the scope of a program and are not easily avoidable. The C++ standard library provides the following classes for runtime errors:
• An exception of class range_error is used to report a range error in internal computations.
• An exception of class overflow_error is used to report an arithmetic overflow.
• An exception of class underflow_error is used to report an arithmetic underflow.


Exceptions Thrown by the Standard Library
The C++ standard library itself can produce exceptions of classes range_error, out_of_range, and invalid_argument. However, because language features as well as
user code are used by the library, their functions might throw any exception indirectly. In particular, bad_alloc exceptions can be thrown whenever storage is allocated.
Any implementation of the standard library might offer additional exception classes (either as siblings or as derived classes). However, the use of these nonstandard classes makes code nonportable because you could not use another implementation of the standard library without breaking your code. So, you should always use only the standard exception classes.


Header Files for Exception Classes
The base class exception and class bad_exception are defined in <exception>. Class bad_alloc is defined in <new>. Classes bad_cast and bad_typeid are defined in
<typeinfo>. Class ios_base::failure is defined in <ios>. All other classes are defined in <stdexcept>.

转载于:https://www.cnblogs.com/Podevor/archive/2011/07/05/2788148.html

### C++ 中的异常处理教程与最佳实践 #### 异常处理机制概述 C++ 提供了一种结构化的错误处理方式——异常处理。当程序遇到无法继续执行的情况时,可以抛出一个异常对象来表示这种状态。捕获并处理这些异常可以使程序更加健壮和可靠。 为了使 C++ 方法能够被托管代码调用,C++ 的异常需要映射到返回值或输出参数中[^1]。这允许托管环境识别发生的错误,并可以选择性地通过抛出托管异常的方式传播原始 C++ 异常。 #### 抛出异常 在 C++ 中,`throw` 关键字用于引发异常: ```cpp if (error_condition) { throw std::runtime_error("An error has occurred"); } ``` 这里创建了一个 `std::runtime_error` 对象作为异常实例传递给运行时系统去寻找匹配的处理器。 #### 捕捉异常 使用 try-catch 块捕捉可能产生的异常: ```cpp try { // 可能会抛出异常的操作 } catch(const std::exception& e) { // 处理标准库中的任何异常类型 std::cerr << "Caught exception: " << e.what() << '\n'; } catch(...) { // 捕获所有未指定类型的异常 std::cerr << "Unknown exception caught\n"; } ``` #### 资源管理与 RAII 资源获取即初始化(RAII)是一种重要的编程模式,在 C++ 编程中有广泛应用。它确保了即使发生异常也能正确释放资源。通常情况下,应该利用智能指针或其他容器类自动管理动态分配的对象生命周期。 #### 设计良好的 API 接口 设计优雅且易于使用的接口对于提高开发效率至关重要。遵循 Qt 风格的设计原则有助于构建直观易懂的 C++ 库函数[^2]。例如,保持一致性的命名约定、提供清晰文档说明以及合理运用模板技术等都是良好做法的一部分。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值