【问题标题】:Is there a way to have exceptions work indefinitely?有没有办法让异常无限期地工作?
【发布时间】:2020-06-27 08:00:42
【问题描述】:

我一直在尝试从用户那里获取输入。我想确保输入满足我对使用 try 和 catch 块的其余代码的要求。

但是,仅捕获一次后,它就会中止代码。我想确保在捕获错误后它实际上会多次返回输入函数,直到用户为程序提供有效输入。除了完全不使用 try catch 块之外,还有其他方法吗?

代码如下:

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

long num; // I need num as global

long get_input()
{
    string input;
    long number;

    cout << "Enter a positive natural number: ";
    cin >> input;

    if ( !(stol(input)) ) // function for string to long conversion
        throw 'R';

    number = stol(input);

    if (number <= 0)
        throw 'I';

    return number;
}

int main()
{
    try
    {
        num = get_input();
    }
    catch (char)
    {
        cout << "Enter a POSTIVE NATURAL NUMBER!\n";
    }

// I want that after catch block is executed, the user gets chances to input the correct number 
// until they give the right input.

    return 0;
}

【问题讨论】:

  • 您想重试某些事情,直到满足某个条件。这就是循环的定义。为什么不使用一个?毕竟,您不必在循环之外捕捉。
  • 那么异常处理程序就没有办法重复了吗?
  • 您离开try 块。这就是例外的原因。如果您想再次尝试,请重复执行它。这就是循环的用途。请参阅现在给出的答案。但这仍然有一个循环。你不使用循环的目的是什么?
  • 好吧,我只是想尝试一些新的例外,仅此而已。 Kitsue 的回答似乎很有道理。

标签: c++ exception c++17


【解决方案1】:

您需要明确编写这样的处理,例如通过循环:

int main()
{
    while (1) {
        try
        {
            num = get_input();
            return 0; // this one finishes the program
        }
        catch (char)
        {
            cout << "Enter a POSTIVE NATURAL NUMBER!\n";
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多