C++ 上的异常
Exceptions on c++
>我有这个:
// exception::what
#include <iostream> // std::cout
#include <exception> // std::exception
struct ooops : std::exception {
const char* what() const noexcept {return "Ooops!n";}
};
class A: std::exception{
public:
int tt;
int getTT(int rr){
if (rr ==5) throw ooops();
return rr;
};
};
int main () {
try {
A testA;
int ww = testA.getTT("kkk");
std::cout << ww << std::endl;//throw ooops();
} catch (std::exception& ex) {
std::cout << ex.what();
}
return 0;
}
我想用上面的字符串调用getTT()
,我想抛出我的异常消息而不是默认消息。我知道如果我从异常类重载方法,我会没问题,但我问是否有更简单的方法可以做到这一点。我正在阅读有关异常的文档,但找不到有用的内容。
你可以扔任何物体。 您不必从std::exception
继承
#include <iostream>
class A{
public:
int tt;
int getTT(int rr){
if (rr ==5) throw "ooops";
return rr;
};
};
int main () {
try {
A testA;
int ww = testA.getTT(5);
std::cout << ww << std::endl;//throw ooops();
} catch (const char* exc) {
std::cout << exc;
}
return 0;
}
如果您不知道异常的类型,可以使用...
,如下所示
#include <iostream>
class A{
public:
int tt;
int getTT(int rr){
if (rr ==5) throw "ooops";
return rr;
};
};
int main () {
try {
A testA;
int ww = testA.getTT(5);
std::cout << ww << std::endl;//throw ooops();
} catch (...) {
std::cout << "exception has been thrown";
}
return 0;
}
你的ooops
类应该派生自std::runtime_error
,它将用户定义的字符串作为输入,并覆盖what()
以返回该字符串。
您的代码中还有其他错误。A
不应该源于std::exception
。A::getTT()
将int
作为输入,但您正在尝试向其传递字符串文字(const char[4]
(。
试试这个:
#include#include #include<字符串>结构哎呀:标准::runtime_error { ooops(const std::string &what_arg = "Ooops!"( : runtime_error(what_arg( { } }; A 类 { 公共: int tt; int getTT(int rr( const { 如果 (rr == 5( 抛出 ooops("rr 不能是 5"(; 返回 RR; } }; int main (( { 尝试 { 测试A; int ww = testA.getTT(5(; std::cout <<ww <<std::endl;抛出哎呀((; } catch (const std::exception& ex( { std::cout <<ex.what(( <<std::endl; } 返回 0; }字符串>
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常