throw问题(C++):throw只能在try_catch throw结构中运用吗?单独运用为什么不行?例1简单测试程序:#include<iostream>using namespace std;int main(void){throw("1");return 0;}程序运行出错:例2:Salary::Salary()//

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/12 17:17:28
throw问题(C++):throw只能在try_catch throw结构中运用吗?单独运用为什么不行?例1简单测试程序:#include<iostream>using namespace std;int main(void){throw(

throw问题(C++):throw只能在try_catch throw结构中运用吗?单独运用为什么不行?例1简单测试程序:#include<iostream>using namespace std;int main(void){throw("1");return 0;}程序运行出错:例2:Salary::Salary()//
throw问题(C++):throw只能在try_catch throw结构中运用吗?单独运用为什么不行?
例1简单测试程序:
#include<iostream>
using namespace std;
int main(void){
throw("1");
return 0;
}
程序运行出错:

例2:
Salary::Salary()// 无参构造函数
{
ifstream iFile("salary.dat");// 建立输入文件
if (iFile.fail())
{// 打开文件失败,表示不存在文件
ofstream oFile("salary.dat");// 建立输出文件
if (oFile.fail()) throw("打开文件失败!");// 抛出异常 
oFile.close();// 关闭文件
}
else
{// 存在文件
iFile.close();// 关闭文件
}


file.open("salary.dat",ios::in|ios::out|ios::binary);// 以读写方式打开文件
}
上边的例1不行,为什么:if (oFile.fail()) throw("打开文件失败!");却可以呢?



throw问题(C++):throw只能在try_catch throw结构中运用吗?单独运用为什么不行?例1简单测试程序:#include<iostream>using namespace std;int main(void){throw("1");return 0;}程序运行出错:例2:Salary::Salary()//
上边的例子1实际上是正确的,因为你自己的main函数抛出了异常没有处理,则系统会调用abort函数来处理你的异常,就是弹出那个框框,抛出了异常,往往是调用者来处理改异常,如果调用者没有处理则找调用者的调用者,如果main函数也没处理,则由操作系统来处理,也就是弹那个框框