有没有一种方法可以使异常无限期地工作? [英] Is there a way to have exceptions work indefinitely?

查看:42
本文介绍了有没有一种方法可以使异常无限期地工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从用户那里获取输入.我想确保输入内容符合我对使用try and catch块的其余代码的要求.

I have been trying to take an input from the user. I want to ensure that the input meets my requirements for the rest of the code for which I have used a try and catch block.

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

However, after only one time catching, it aborts the code. I want to ensure that after catching error it actually goes back to the input function for as many times until the user gives the program a valid input. Is there a way to do that except not using try catch blocks altogether?

代码如下:

#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;
}

推荐答案

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

You need explicitly write such a handling, e.g. via loop:

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

这篇关于有没有一种方法可以使异常无限期地工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆