![](https://img.haomeiwen.com/i11218161/c0501d24f9c618b3.png)
1).c++抛出来的异常, 在java层try是没有用的
2)同一个 try 语句可以跟上多个 catch 语句(在工程中,将可能产生异常的代码放在 try 语句块中,然后后面跟上多个 catch 语句);
3)try 语句中通过 throw 关键字 可以抛出任何类型的异常(int、字符串、对象,引用等等);
4)catch 语句可以定义具体处理的异常类型,如 catch( int ) 只捕获 int 类型异常, 但无法进一步获取异常信息;catch( int a ) 只捕获 int 类型异常,可以进一步获取异常信息
C++ 标准库中的异常类
out_of_range:
intmain(intargc,char*argv[])
66{
67try
68{
69Array<int,5>arr;
70
71arr.print();
72arr[-1]=1;// 异常测试
73arr.print();
74}
75
76catch(constout_of_range&e)// 1 使用 const 引用类型作为参数 2 赋值兼容性原则(参考第4点)
77{
78cout<<e.what()<<endl;
79}
80
81catch(...)
82{
83cout<<"other exception ... "<<endl;
84}
85
86return0;
87}
88
标准异常的种类和描述
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 当发生数学下溢时,会抛出该异常。
————————————————
函数的异常声明列表
void func() throw (int, double, A, B, C){...}
定义新的异常:
可以使用继承和重载exception类来定义新的异常。
使用std::exception类来实现自己的异常。
#include<iostream>
#include<exception>
usingnamespacestd;
structMyException:publicexception
{
constchar*what()constthrow()
{
return"C++ Exception";
}
};
intmain()
{
try
{
throwMyException();
}
catch(MyException&e)
{
std::cout<<"MyException caught"<<std::endl;
std::cout<<e.what()<<std::endl;
}
catch(std::exception&e)
{
//其他的错误
}
}
网友评论