📄 异常处理.txt
字号:
//**************************
//** ch21_1.cpp **
//**************************
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
void main(int argc,char** argv)
{
ifstream source(argv[1]);
char line[128];
try
{
if(source.fail())
throw argv[1];
}
catch(char* s)
{
cout<<"error opening the file "<<s<<endl; //实际运行中,不会打印出这行错误信息,而是新建一个空的与argv[1]同名的新文件。
exit(1);
}
while(!source.eof())
{
source.getline(line,sizeof(line));
cout<<line<<endl;
}
source.close();
}
//**************************
//** ch21_2.cpp **
//**************************
#include <iostream.h>
double Div(double,double);
void main()
{
try
{
cout<<"7.3/2.0="<<Div(7.3,2.0)<<endl;
cout<<"7.3/0.0="<<Div(7.3,0.0)<<endl;
cout<<"7.3/1.0="<<Div(7.3,1.0)<<endl;
}
catch(double)
{
cout<<"except of deviding zero."<<endl;
}
cout<<"That is OK!"<<endl;
}
double Div(double a,double b)
{
if(b==0)
throw b;
return a/b;
}
//**************************
//** ch21_3.cpp **
//**************************
#include <iostream.h>
#include <string.h>
class String
{
public:
String(char*,int);
class Range
{
public:
Range(int j):index(j) {}
int index;
};
class Size{};
char& operator [] (int k)
{
if(0<=k && k<len)
return p[k];
throw Range(k);
}
private:
char* p;
int len;
static int max;
};
int String::max=20;
String::String(char* str,int si)
{
if(si<0||max<si)
throw Size();
p=new char[si];
strncpy(p,str,si);
len=si;
}
void g(String& str)
{
int num=10;
for(int n=0;n<num;n++)
cout<<str[n];
cout<<endl;
}
void f()
{
//code segment 1
try
{
//code segment 2
String s("abcdefghijklmnopqrstuvwxyz",10);
g(s);
}
catch(String::Range r)
{
cerr<<"->out of range:"<<r.index<<endl;
//code segment 3
}
catch(String::Size)
{
cerr<<"size illegal!"<<endl;
}
cout<<"The program will be continued here."<<endl;
//code segment 4
}
void main()
{
//code segment 5
f();
cout<<"These code is not effected by probably exception in f()."<<endl;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -