C++ 上的异常

Exceptions on c++

本文关键字:异常 C++      更新时间:2023-10-16

>我有这个:

// 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::exceptionA::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; }