21xrx.com
2024-09-19 09:53:20 Thursday
登录
文章检索 我的文章 写文章
C++自定义异常的方法和示例
2023-07-08 09:55:29 深夜i     --     --
C++ 自定义异常 方法 示例

C++是一门强大的编程语言,支持自定义异常,编程人员可以通过自己写的异常类创建自定义异常对象并在合适的地方抛出,从而使程序更加健壮。

下面是一些自定义异常的方法和示例:

方法一:继承std::exception

继承std::exception是最常见的一种方法,如下所示,我们创建了一个名为MyException的异常类,继承自std::exception,重载了what()方法,将异常信息以字符串的形式返回。


#include <exception>

#include <string>

class MyException : public std::exception {

public:

 MyException(const std::string& msg) : msg_(msg) {}

 virtual const char* what() const noexcept override {

  return msg_.c_str();

 }

private:

 std::string msg_;

};

在使用时,我们可以像使用其他异常一样,通过throw语句抛出自定义异常对象。


try {

 throw MyException("Something went wrong!");

} catch (const std::exception& e) {

 std::cout << e.what() << std::endl;

}

方法二:继承std::runtime_error

除了继承std::exception,我们还可以继承std::runtime_error,这样可以更加方便地返回异常信息。


#include <stdexcept>

#include <string>

class MyException : public std::runtime_error {

public:

 MyException(const std::string& msg) : runtime_error(msg) {}

};

可以看到,这里直接在构造函数中调用了父类的构造函数,将异常信息传给了std::runtime_error。在使用时也与上述方法一样。

方法三:使用宏定义

使用宏定义可以更进一步地简化自定义异常的操作,如下所示:


#define THROW_EXCEPTION(cls, msg) \

 do { \

  cls ex(msg); \

  throw ex; \

 } while (0)

class MyException : public std::runtime_error {

public:

 MyException(const std::string& msg) : runtime_error(msg) {}

};

...

try {

 THROW_EXCEPTION(MyException, "Something went wrong!");

} catch (const std::exception& e) {

 std::cout << e.what() << std::endl;

}

这里定义了一个宏,可以在抛出自定义异常时使用,传入自定义异常类和异常信息即可。

总结:

通过继承std::exception或std::runtime_error或者使用宏定义,我们可以很方便地自定义异常,并在程序中使用。自定义异常可以让程序更健壮,使异常处理更加精准和方便。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复