📜  C++异常处理

📅  最后修改于: 2020-10-16 07:15:01             🧑  作者: Mango

Throw

C++异常处理

C++中的异常处理是处理运行时错误的过程。我们执行异常处理,因此即使在运行时错误之后,也可以保持应用程序的正常流程。

在C++中,异常是在运行时引发的事件或对象。所有异常均源自std :: exception类。这是可以解决的运行时错误。如果我们不处理异常,它将打印异常消息并终止程序。

优点

它保持了应用程序的正常流程。在这种情况下,即使在异常发生后,其余代码也会执行。

C++异常类

在C++中,标准例外是在我们可以在程序中使用的类。父子类层次结构的安排如下所示:

C++中的所有异常类均源自std :: exception类。让我们看一下C++常见异常类的列表。

Exception Description
std::exception It is an exception and parent class of all standard C++ exceptions.
std::logic_failure It is an exception that can be detected by reading a code.
std::runtime_error It is an exception that cannot be detected by reading a code.
std::bad_exception It is used to handle the unexpected exceptions in a c++ program.
std::bad_cast This exception is generally be thrown by dynamic_cast.
std::bad_typeid This exception is generally be thrown by typeid.
std::bad_alloc This exception is generally be thrown by new.

C++异常处理关键字

在C++中,我们使用3个关键字执行异常处理:

  • try
  • catch
  • throw

此外,我们可以创建用户定义的异常,我们将在下一章中学习。