#include <iostream>
#include <stdio.h>
using namespace std;
/*异常---错误但能处理的*/
//传统异常处理
int my_copy(const char* in_file, const char* out_file){
FILE *src_file, *dest_file;
if ( (src_file = fopen(in_file, "rb")) == NULL )
//return -1; //传统异常处理
throw "打开源文件出错"; //throw抛出异常//字符串类型
if ( (dest_file = fopen(out_file,"wb")) == NULL )
//return -2;
throw -2;
char buf[8];
size_t in_byte, out_byte;
while ( (in_byte = fread(buf,1,8,src_file)) > 0 )
{
out_byte = fwrite(buf,1,in_byte,dest_file);
if (in_byte != out_byte)
//return -3;
throw -3;
}
fclose(dest_file);
fclose(src_file);
//return 0; //抛出异常,可以不需要返回值
}
int main()
{
//传统异常处理
// int flag;
// flag = my_copy("main.cpp", "out.txt");
//
// switch(flag){
// case -1:
// cout << "in_file loading error!\n";
// break;
// case -2:
// cout << "out_file loading error!\n";
// break;
// case -3:
// cout << "write error!\n";
// break;
// case 0:
// cout << "copy successfully!\n";
// break;
// }
//抛出异常
try{
my_copy("main.cpp", "out.txt");
}catch(int e){
cout << "异常代码:" << e << endl;
}catch(const char* e){
cout << "ERROR: " << e << endl; //e为局部变量
}catch(...){
cout << "Error\n";
}
return 0;
}
//1. c++是面向对象的,最好的方法是抛出对象。
//2. 多个对象需要catch多次。
// 太多时不好一个一个写,所以可以用:catch(...)获取所有异常
// 即:前面先获取具体重要的异常,后面的用catch(...)捕获
//3. 只有一次异常的机会,一旦捕获异常,直接跳到catch块,后面的代码不再执行。