Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 显示案例中的错误。C++;_C++_Validation_Input_Output_Return Value - Fatal编程技术网

C++ 显示案例中的错误。C++;

C++ 显示案例中的错误。C++;,c++,validation,input,output,return-value,C++,Validation,Input,Output,Return Value,在这种情况下,如何向客户端显示代码错误 以下是某人将使用的功能: double firstTaskSum(int n, double x) { if(n < 0) { cout << ("n is invalid! n : " + std::to_string(n) + ". And must be n >= 0."); return; } if(x == 0) { cout <

在这种情况下,如何向客户端显示代码错误

以下是某人将使用的功能:

double firstTaskSum(int n, double x)
{
    if(n < 0)
    {
        cout << ("n is invalid! n : " + std::to_string(n) + ". And must be n >= 0.");
        return;
    }

    if(x == 0)
    {
        cout << ("x is invalid! 0 to power of 0 is undefined.");
        return;
    }

    return firstTaskSumUp(0, n, x, 1, 1);
}
double firstTaskSum(整数n,双x)
{
if(n<0)
{

cout您可以引发异常:

#include <stdexcept>
using namespace std;

double firstTaskSum(int n, double x)
{
    if (n < 0)
    {
        throw invalid_argument("n must be positive");
    }

    if (x == 0)
    {
        throw invalid_argument("x can't be 0");
    }

    return firstTaskSumUp(0, n, x, 1, 1);
}
#包括
使用名称空间std;
双firstTaskSum(整数n,双x)
{
if(n<0)
{
抛出无效的_参数(“n必须为正”);
}
如果(x==0)
{
抛出无效的_参数(“x不能为0”);
}
返回firstTaskSummup(0,n,x,1,1);
}

除了抛出异常之外,另一个选项是对参数有效性进行函数检查

if (IsArgumentValid(1, 1))
    firstTaskSum(1, 1);
else
    cout << "Invalid arguments\n";
if(IsArgumentValid(1,1))
firstTaskSum(1,1);
其他的

不能抛出异常并在上层处理它。我如何捕获
无效的\u参数
异常?例如,我知道我可以使用
catch(const char*msg)
捕获纯文本。@code>catch
的参数类型是:
catch(const invalid \u参数&e)
。如何将作为参数传递给
无效参数的消息输出到
?@如果捕获到异常,可以调用该方法,它将返回构建异常的消息。
if (IsArgumentValid(1, 1))
    firstTaskSum(1, 1);
else
    cout << "Invalid arguments\n";