C++ 标准的异常
2017-02-10 20:04
477 查看
#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; } -------------------------------------------------------------------------------------------------------- #include <iostream> template <typename T> T Div(T x,T y) { if(y==0) throw y;//抛出异常 return x/y; } int main() { int x=5,y=0; double x1=5.5,y1=0.0; try { //被检查的语句 std::cout<<x<<"/"<<y<<"="<<Div(x,y)<<std::endl; std::cout<<x1<<"/"<<y1<<"="<<Div(x1,y1)<<std::endl; } catch(int)//异常类型 { std::cout<<"除数为0,计算错误!"<<std::endl;//异常处理语句 } catch(double)//异常类型 { std::cout<<"除数为0.0,计算错误!"<<std::endl;//异常处理语句 } return 0; } --------------------------------------------------------------------------------------------------------
C++ 提供了一系列标准的异常,定义在 <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 | 当发生数学下溢时,会抛出该异常。 |
您可以通过继承和重载 exception 类来定义新的异常。下面的实例演示了如何使用
std::exception 类来实现自己的异常:
#include
<iostream>#include
<exception>using
namespace std;struct
MyException
:
public exception{
const
char
* what
()
const
throw
()
{
return
"C++ Exception";
}};
int main(){
try
{
throw
MyException();
}
catch(MyException&
e)
{ std::cout
<<
"MyException caught"
<< std::endl;
std::cout
<< e.what()
<< std::endl;
}
catch(std::exception&
e)
{
//其他的错误
}}
这将产生以下结果:
MyException
caughtC++
Exception
在这里,what() 是异常类提供的一个公共方法,它已被所有子异常类重载。这将返回异常产生的原因。
相关文章推荐
- Dev支持C++11
- leetcode:Merge k Sorted Lists (建立堆)
- C++数值与字符串之间的转换
- C++ 中的类型限定符
- C++ 左值(Lvalues)和右值(Rvalues)
- c++之五谷杂粮---3
- 排序算法之堆排序
- c++ 变量和数据类型
- C语言面试题
- leetcode 79. Word Search
- 华为机试在线训练-牛客网(22)字符串加密
- C中的二分函数:upper_bound()与lower_bound()
- 数独C语言解法
- C++中引用、指针与const
- 继承与派生
- C++数据的共享与保护
- 多态性
- c++知识点
- C++ 类复制
- 【转】【c++】指针参数是如何传递内存的