gpt4 book ai didi

c++ - C++中的异常处理问题

转载 作者:太空宇宙 更新时间:2023-11-04 15:27:59 24 4
gpt4 key购买 nike

你好,我是 C++ 编程的新手,需要一些关于我在下面编写的代码的帮助....它是一个基本的异常处理程序

#include<iostream>

class range_error
{
public:
int i;
range_error(int x){i=x;}
}

int compare(int x)
{
if(x<100)
throw range_error(x);
return x;
}

int main()
{
int a;
std::cout<<"Enter a ";
std::cin>>a;
try
{
compare(a);
}
catch(range_error)
{
std::cout<<"Exception caught";
}
std::cout<<"Outside the try-catch block";
std::cin.get();
return 0;
}

当我编译这个...我得到这个...

新类型不能在第 11 行的返回类型中定义(在比较函数的开头)。

请解释一下哪里出了问题...

最佳答案

class range_error
{
public:
int i;
range_error(int x){i=x;}
}; // <-- Missing semicolon.

int compare(int x)
{
if(x<100)
throw range_error(x);
return x;
}

您的代码可能如下所示:

#include <iostream>
#include <stdexcept>

// exception classes should inherit from std::exception,
// to provide a consistent interface and allow clients
// to catch std::exception as a generic exception
// note there is a standard exception class called
// std::out_of_range that you can use.
class range_error :
public std::exception
{
public:
int i;

range_error(int x) :
i(x) // use initialization lists
{}
};

// could be made more general, but ok
int compare(int x)
{
if (x < 100) // insertspacesbetweenthingstokeepthemreadable
throw range_error(x);

return x;
}

int main()
{
int a;
std::cout<<"Enter a ";
std::cin>>a;

try
{
compare(a);
}
catch (const range_error& e) // catch by reference to avoid slicing
{
std::cout << "Exception caught, value was " << e.i << std::endl;
}

std::cout << "Outside the try-catch block";
std::cin.get();

return 0; // technically not needed, main has an implicit return 0
}

关于c++ - C++中的异常处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4007362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com