异常的基础知识
异常:程序在执行时发生的特殊情况。无法在编译阶段被识别出来,一般的c++错误在程序编译时就会被识别并抛出。
throw:发生异常时由throw抛出。
try:try{ }中用于书写发生异常的代码段
catch:catch(){ }捕捉特定类型的异常,对异常进行一定的处理。
throw与try{}catch(){}的简单运用
char const *类型的异常
/*
异常的使用
*/
#include <iostream>
using namespace std;
#include <string>
int abc(int a, int b, int c){
//如果a,b,c中有<=0的数,就抛出异常
if(a <= 0 || b <= 0 || c <= 0){
throw "illegal parameters";
}
return a + b * c;
}
int main(){
try{
cout <<abc(1, 1, 0) <<endl; //在运行abc()时可能会抛出异常
}
catch(char const* e){ //捕捉char const* 类型的异常
cout << "The parameters to abc were 1, 1, and 0" << endl; //一些输出处理
cout << "illegalParameterValue exception thrown" << endl;
cout << e <<endl;
return 1;
}
return 0;
}
int 型的异常
/*
《数据结构、算法与应用 c++语言描述》
Page 8 第10题
*/
#include <iostream>
using namespace std;
int abc(int a, int b, int c){
if(a < 0 && b < 0 && c < 0){
throw 1;
}
else if(a==0 && b==0 && c==0){
throw 2;
}
return a + b * c;
}
int main(){
//实例1:输出 bomb!! exception2
try{
cout <<abc(0, 0, 0) <<endl;
}
catch(int e){
cout <<"bomb!! exception"<<e<<endl;
//return 1;
}
//实例2:输出 bomb!! exception1
try{
cout <<abc(-1, -1, -1) <<endl;
}
catch(int e){
cout <<"bomb!! exception"<<e<<endl;
//return 1;
}
//实例3:输出 2
try{
cout <<abc(1, 1, 1) <<endl;
}
catch(int e){
cout <<"bomb!! exception"<<e<<endl;
//return 1;
}
return 0;
}
异常类的编辑与使用
/*
一个简单的异常类---面向对象的设计
*/
#include <iostream>
using namespace std;
#include <string>
//参数异常类
class illegalParameterValue
{
public:
illegalParameterValue(){
message = "Illegal parameter value";
}
illegalParameterValue(char * theMessage){
message = theMessage;
}
void output(){
cout <<message<<endl;
}
private:
string message;
};
//功能函数
int abc(int a, int b, int c){
if(a < 0 || b <0 || c < 0){
throw illegalParameterValue();
}
else if(a==0 && b==0 && c==0){
throw illegalParameterValue("All parameters are equal to 0");
}
return a + b * c;
}
//main函数中测试
int main(){
//实例1:输出 All parameters are equal to 0
try{
cout <<abc(0, 0, 0) <<endl;
}
catch(illegalParameterValue e){
e.output();
}
//实例2:输出 Illegal parameter value
try{
cout <<abc(-1, -1, -1) <<endl;
}
catch(illegalParameterValue e){
e.output();
}
//实例3:输出 2
try{
cout <<abc(1, 1, 1) <<endl;
}
catch(illegalParameterValue e){
e.output();
}
return 0;
}
对书中的一个小问题的解决
《数据结构、算法与应用 c++语言描述》第二版一书中(P7、P8)给出了如下类型的代码:
#include <iostream>
using namespace std;
#include <string>
int abc(int a, int b, int c){
if(a <= 0 || b <= 0 || c <= 0){
throw "illegal parameters";
}
return a + b * c;
}
int main(){
try{
cout <<abc(1, 1, 0) <<endl;
}
catch(char* e){
cout << "The parameters to abc were 1, 1, and 0" << endl;
cout << "illegalParameterValue exception thrown" << endl;
cout << e <<endl;
return 1;
}
return 0;
}
书中说这个程序抛出的异常类型是char*,但在运行时出现了如下情况(terminate called after throwing an instance of ‘char const*’):
显然程序出现了一个char const* 类型的异常,及通过throw " "抛出的异常是char const* 类型的,而不是char* 类型的。具体原因我也不清楚,难道是编译器的原因???
c++指针使用详解可能会对你理解char* 与char const* 甚至是const char *的区别有所帮助。