概述
C++中的異常是以繼承的方式展現出來的,exception只是一個抽象類,通過虛函數的方式來進行繼承,可以達到C++多態的效果。直接可以使用父類指針或者引用來捕獲異常。
詳細介紹
bad_typeid
在使用typeid運算符時,如果其操作數是一個多態類型的指針,而該指針的值爲NULL時,則會拋出異常。
#include<iostream>
#include<typeinfo>
using namespace std;
class Base
{
public:
virtual void Func()
{}
};
int main()
{
try
{
Base *bp = 0;
cout << typeid(*bp).name() << endl;
}
catch (exception& bt)
{
cerr << "bad_typeid caught: " << bt.what() << endl;
}
}
bad_cast
在使用dynamic_cast()進行從多態基類對象(或引用)到派生類對象(或引用)的強制類型轉化時,如果類型是不安全的,則會拋出異常
class Base
{
public:
virtual void Func()
{}
};
class Derived : public Base
{};
int main()
{
try
{
Base b;
Derived& rd = dynamic_cast<Derived&>(b);
}
catch (exception& bc)
{
cerr << "bad_cast caught: " << bc.what() << endl;
}
}
bad_alloc
這個是最熟悉的:在使用new運算符進行動態內存分配時,如果沒有足夠的空間可分配,則會引發此類異常
int main()
{
try
{
int * arr;
while(1)
arr = new int[100000000];
}
catch (exception& ba)
{
cerr << "bad_alloc caugth: " << ba.what() << endl;
}
}
out_of_range
數組字符串等下標越界,拋出訪問越界異常
#include<vector>
int main()
{
vector<int> v(10);
try
{
v.at(20) = 10; //at函數會拋異常
//下標訪問運算符則是報錯
}
catch (exception& oor)
{
cerr << "out_of_range caugth: " << oor.what() << endl;
}
}
runtime_error
從基類(exception)中派生,報告運行時錯誤,只有在程序運行時,這類錯誤纔會被檢測到。
(例子有點難舉emmm)
ios_failure
這個繼承自標準異常類,它是iostream類層次結構中的成員函數拋出異常的對象的基類。
invalid_argument
#include<bitset>
int main()
{
try
{
bitset<5> set(string("01234"));
}
catch (exception& ia)
{
cerr << "run_time caugth: " << ia.what() << endl;
}
}
length_error
表明當一個程序試圖產生一個比npos長度還要大的對象
#include <vector>
int main()
{
try {
vector<int> myvector;
myvector.resize(myvector.max_size() + 1);
}
catch (length_error& le) {
cerr << "Length error: " << le.what() << endl;
}
return 0;
}