简单的说,异常就是代码出现不正常,有了神经病。哈哈哈哈。。。。。。就像单片机代码中,出现异常代码跑飞了,看门狗没喂狗,产生复位。
异常是程序执行过程期间产生的问题,比如当除数为0时的操作,这是一个有问题的操作。在C语言中,这个有问题的操作是通过条件判断来审判这个骚操作是否真确。而面向对象语言通过异常方式来实现转义程序控制权。
C++异常提供了三个关键字:
throw:当程序出现异常时,将异常抛出。
catch:捕获程序的异常。
try:try 块中的代码标识将被激活的特定异常,通常跟着一个或多个catch 块。
异常捕获:
当程序抛出异常时,使用try和catch捕获异常。try块中放置可能出现异常的代码,其代码也称为保护代码,catch块中放置捕获带异常后的处理方法。
try
{
// 保护代码
}catch( ExceptionName e1 )
{
// catch 块
}catch( ExceptionName eN )
{
// catch 块
}
异常抛出:
C++提供关键字throw,它可以在任意位置抛出异常,其中throw的操作数可以使任意的表达式,表达式的类型,决定抛出异常的类型。
cin >> a;
cin >> b;
if(b == 0)
{
throw "error";
}
else
{
c = a/b;
}
try、catch、throw三个关键字的使用方法,例子:
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}
catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}
C++提供了一系列标准的异常,需包含头文件#include <exception>
异常 | 描述 |
---|---|
std::exception | 该异常是所有标准 C++ 异常的父类。 |
std::bad_alloc | 该异常可以通过 new 抛出。 |
std::bad_cast | 该异常可以通过 dynamic_cast 抛出。 |
std::bad_exception | 这在处理 C++ 程序中无法预期的异常时非常有用。 |
std::bad_typeid | 该异常可以通过 typeid 抛出。 |
std::logic_error | 理论上可以通过读取代码来检测到的异常。 |
std::domain_error | 当使用了一个无效的数学域时,会抛出该异常。 |
std::invalid_argument | 当使用了无效的参数时,会抛出该异常。 |
std::length_error | 当创建了太长的 std::string 时,会抛出该异常。 |
std::out_of_range | 该异常可以通过方法抛出,例如 std::vector 和 std::bitset<>::operator[]()。 |
std::runtime_error | 理论上不可以通过读取代码来检测到的异常。 |
std::overflow_error | 当发生数学上溢时,会抛出该异常。 |
std::range_error | 当尝试存储超出范围的值时,会抛出该异常。 |
std::underflow_error | 当发生数学下溢时,会抛出该异常。 |
C++允许通过继承和重载 exception 类来定义自己的异常处理。例子:
#include <iostream>
#include <exception>
using namespace std;
struct user_exc : public exception
{
const char * what () const throw ()
{
return "User Exception";
}
};
int main()
{
try
{
throw user_exc();
}
catch(user_exc& e)
{
cout << "User Exception caught" << endl;
cout << e.what() << endl;
}
}
本文分享自 Rice 嵌入式开发技术分享 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!