C++中的異常處理與模板類
一、C++ 中的異常處理
1、異常處理
在C++ 中可以拋出任何類型的異常,根據(jù)拋出的異常數(shù)據(jù)類型,進入到相應的 catch塊中 ,未知類型可用 ... 代替
void main() {
try {
int a = 300;
if (a > 200) {
throw - 1;
}
}
catch (int a) {
cout << a << endl;
}
try {
int b = 0;
if (b == 0) {
throw "不能為0";
}
}
catch (const char* b) {
cout << b << endl;
}
try {
int c = -1;
if (c < 0 ) {
throw 0.1;
}
}
catch (...) {
cout << "未知異常" << endl;
}
getchar();
}
2、throw 拋出函數(shù)外
float div2(float a, float b) {
if (b == 0) {
throw "除數(shù)為零";
}
return a / b;
}
void main() {
try {
float c = div2(8, 0);
}
catch (const char* e) {
cout << e << endl;
}
getchar();
}
3、拋出異常對象
拋出異常對象可以使用異常對象來捕獲異常或者使用異常對象的引用來捕獲異常,采用引用方式不會產(chǎn)生副本(可實現(xiàn)拷貝構(gòu)造函數(shù)來驗證);盡量不要拋出異常指針(new 動態(tài)內(nèi)存),需要delete動態(tài)內(nèi)存
//異常類
class MyException {
public:
MyException() {
}
};
float div2(float a, float b) {
if (b == 0) {
//拋出對象
throw MyException();
//拋出異常指針
throw new MyException;
}
return a / b;
}
void main() {
try {
float c = div2(8, 0);
}
//catch (MyException e) {//對象,被拷貝了對象,產(chǎn)生對象副本
// cout << "MyException" << endl;
//}
catch (MyException &e1) {//對象的引用,效率更高
cout << "MyException引用" << endl;
}
//catch (MyException* e2) {//異常指針,需要delete
// cout << "MyException指針" << endl;
// delete e2;
//}
getchar();
}
4、聲明拋出異常的類型
throw 加載函數(shù)名稱上,表示聲明函數(shù)會拋出的異常類型
float div2(float a, float b) throw(char*,int) {
if (b == 0) {
throw "除數(shù)為零";
}
return a / b;
}
void main() {
try {
float c = div2(8, 0);
}
catch (const char* e) {
cout << e << endl;
}
getchar();
}
5、標準異常(類似于Java NullPointerException)
class NullPointerException : public exception{
public:
NullPointerException(char* msg) : exception(msg){
}
};
float div2(float a, float b) throw(char*,int) {
if(b == NULL){
throw NullPointerException("is NULL");
} else if (b > 10000) {
throw out_of_range("超出范圍");
}else if(b == 0){
throw invalid_argument("參數(shù)不合法");
}
return a / b;
}
void main() {
try {
float c = div2(8, 0);
}
catch (out_of_range e) {
cout << e.what() << endl;
}
catch (NullPointerException& e1) {
cout << e1.what() << endl;
}
catch (...) {
cout << "未知異常" << endl;
}
getchar();
}
二、模板類
屬性或者構(gòu)造函數(shù)中存在泛型參數(shù)的類叫模板類
1、模板類示例
template<class T>
class A{
public:
A(T a){
this->a = a;
}
protected:
T a;
};
2、普通類繼承模板類
class B : public A<int>{
public:
B(int a,int b) : A<int>(a){
this->b = b;
}
private:
int b;
}
3、模板類繼承模板類
template<class T>
class C : public A<T>{
public:
C(T a,T c) : A<T>(a){
this->c = c;
}
protected:
T c;
}
4、模板類對象實例化
void main(){
//實例化模板類對象
A<int>(6);
getchar();
}