当前位置: 代码迷 >> 综合 >> C++异常处理(C++ Exception Handling)----1
  详细解决方案

C++异常处理(C++ Exception Handling)----1

热度:62   发布时间:2023-12-15 16:50:24.0

一、问题的提出:

上午看到一段处理异常的代码,我试图在Visual C++ 6.0中运行,代码如下:

#include<iostream>
#include<stdexcept>

using namespace std;

int main()
{
 try{
  int ival=68;
  int ival2;
  cout<<"Please input the num:";
  cin>>ival2;
  cout<<ival<<"/"<<ival2<<"="<<(ival/ival2)<<endl;
 }
 catch(exception ex){//注意红色字体部分
  cout<<"ERROR:"<<endl;
 }

 return 0;

运行界面如下:

Please input the num:0

68/0=

弹出对话框提示非法操作,(与本代码所要求的抛出异常信息完全不符合)

为什么不能正常运行?

二、解决方法:

将代码中的红色部分改成catch(...)即可。

运行界面如下:

Please input the num:0

68/0=ERROR

  相关解决方案