【问题标题】:Throw Exception when a wrong type is keyed in键入错误类型时抛出异常
【发布时间】:2017-05-04 05:21:39
【问题描述】:

我必须编写一个 C++ 程序,其中的一个函数是从键盘读取两个 double 类型数字并添加一个 try 块以在键入错误类型时抛出异常。我使用了 cin.fail()功能,但它不起作用。

这是我迄今为止尝试过的,但如果我输入双精度值,它不会抛出异常。

#include<iostream>
#include<conio.h>
using namespace std;


int main() 
{

    double j;
    try{
        cin>>j;
        if (cin.fail())
            throw (j);
        else
            cout << "Double Value " << j << endl;  
    }
    catch(double a)
    {
        cout<<"Incompatible Datatype for value"<<a;
    }

}

【问题讨论】:

  • 旁注:输入错误数据的人不是需要抛出异常的异常情况。在 C++ 中,应该为那些 异常 情况保留异常,而不是如果某人的手指很粗并且按错了键盘上的键。
  • 这是程序的完整定义。编写以下程序 • 一个从键盘读取两个双精度类型数字的函数 • 一个计算这两个数字相除的函数 • 一个 try 块,用于在键入错误类型时抛出异常 • 一个 try 块,用于检测和如果出现“被零除”条件,则抛出异常 • 适当的 catch 块来处理抛出的异常
  • 但它不起作用。 -- 这不是一个充分的描述。请描述您看到的结果,以及您期望的结果。您的作业也明确声明要输入两个双打,那么为什么将您的类型声明为int
  • @Bhagyasripatel 根据您的描述,您必须阅读 double 值。在您的代码示例中,您使用int i;cin &gt;&gt; i;。如果我理解正确,应该是double i;
  • @Bhagyasripatel 输入的整数值有效的双精度值。如果类型是double,输入123没有错。

标签: c++ exception-handling


【解决方案1】:

捕获字符串并处理异常呢? 大致思路如下:

string d;

    try{
        cin >> d;
        if ( d.find_first_not_of("0123456789-+.") != string::npos)
        {
            throw std::runtime_error("not an int");
        }
        else if ( ( strtod( d.c_str(),nullptr ) > INT_MAX ) || ( strtod( d.c_str(),nullptr ) < INT_MIN ) )
        {
            throw std::runtime_error(" int overflow");
        }

    }
    catch(const std::exception&d)
    {
        cout << d.what() << endl;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多