本文共 10228 字,大约阅读时间需要 34 分钟。
c ++异常处理
In this article, we’ll take a look at performing Exception Handling in C++.
在本文中,我们将介绍在C ++中执行异常处理 。
Exception Handling is an important topic, especially in the context of . C++ is similar to Java, with the fact that it can raise and catch Exceptions.
异常处理是一个重要的主题,尤其是在 。 C ++与Java类似,因为它可以引发和捕获Exceptions 。
We denote a separate section of the code to handle exceptions, as they make things modular and easier for programmers. If any additional errors are detected, only the exception handling code must be modified.
我们在代码的单独部分中说明了处理异常的方法,因为它们使事情变得模块化,并使程序员更轻松。 如果检测到任何其他错误,则仅必须修改异常处理代码。
We must enclose any code which throws an exception under a try
block. So the three major parts of Exception Handling are:
我们必须将任何引发异常的代码放在try
块下。 因此,异常处理的三个主要部分是:
try
block try
块 throw
keyword. 使用可选对象以及throw
关键字throw
异常。 catch
block, to handle the Exception. This block is usually immediately after the try
block. The program will jump to this section immediately after a suitable exception is thrown. 一个catch
块,用于处理Exception。 该块通常紧接在try
块之后。 引发适当的异常后,程序将立即跳至本节。 The overall structure of the program will be:
该计划的总体结构为:
try { ... throw exception;}catch(object) { ...}
Let’s investigate this in more detail, in the below sections.
让我们在以下部分中对此进行更详细的研究。
In C++ terms, we call the raising of an exception as throwing an exception.
用C ++术语来说,我们将引发异常称为抛出异常。
This is done using the throw
keyword. This can take any object (or a primitive type) and pass it into the exception handling code.
这是使用throw
关键字完成的。 这可以采用任何对象(或原始类型)并将其传递到异常处理代码中。
The syntax for throwing an object is:
抛出对象的语法是:
// Must enclose the code in a try blocktry { int x = 0; call_function(x); if (x < 0) { // Throw the object, if something unwanted happened throw x; }}
Now, the program is obviously not complete, since there is no catch
block.
现在,由于没有catch
块,因此程序显然未完成。
Let’s write that now!
现在就写吧!
We mentioned that the program will jump from the try
block to a suitable catch
block, if available.
我们提到,程序将从try
块跳转到合适的catch
块(如果有)。
A catch
block is of the following structure:
catch
块具有以下结构:
catch(int x) { std::cout << "Exception thrown. Object " << x << " caught.\n"; }
Whenever our function_call(x)
makes x become negative, it will throw an exception, and a message will be printed.
每当我们的function_call(x)
使x变为负数时,它将抛出异常,并显示一条消息。
Let’s look at the complete program now.
现在让我们看一下完整的程序。
#includevoid function_call(int& x) { // Do some work, and modify the value of x, so we're passing by reference if (x == 0) { // Set it to some negative value. We'll use this to throw an exception x = -10; // Throw an exception, and pass the object x throw x; } else { x = 100; }}int main() { int x = 0; try { function_call(x); std::cout << "If this line executes, then x != 0\n"; } catch(int x) { std::cout << "Exception thrown. Object " << x << " caught.\n"; } return 0;}
Since x
was set to 0 initially, we will throw an exception, and print the modified value of x
( set to -10), showing that it has executed the catch
block.
由于最初将x
设置为0,我们将引发异常,并打印x
的修改值(设置为-10),表明它已执行catch
块。
Also, notice that the line immediately below the function_call(x)
statement never gets executed, since the program directly jumps to catch
.
另外,请注意,由于程序直接跳转到catch
,因此function_call(x)
语句正下方的行永远不会执行。
Output
输出量
Exception thrown. Object -10 caught.
What if you want your code to handle all arbitrary kinds of exceptions? C++ introduces a feature which allows you to perform this, using a special matching object using ...
.
如果您希望代码处理所有任意种类的异常该怎么办? C ++引入了一项功能,该功能允许您使用特殊的匹配对象...
来执行此操作。
To catch all kinds of exceptions, we can write catch(...)
to catch every object that we throw. This is called the Default Exception and is the fallback option, when we cannot match with any of the other exceptions.
为了捕获各种异常,我们可以编写catch(...)
来捕获我们抛出的每个对象。 当我们无法与其他任何异常匹配时,这称为默认异常 ,它是后备选项。
To illustrate this, here is an example.
为了说明这一点,这是一个示例。
#include#include void function_call(int& x) { // Do some work, and modify the value of x, so we're passing by reference if (x == 0) { // Throw an exception, and pass on the object x throw x; } else if (x < 0) { // If x is negative, throw a random string throw std::string("Default String"); } else { x = 100; }}int main() { for (int i=0; i>=-3; i--) { try { function_call(i); std::cout << "If this line executes, then x != 0\n"; } catch(int x) { std::cout << "Exception thrown. Currently, x = " << x << " caught.\n"; } catch(...) { std::cout << "Default exception. Currently, i = " << i << " caught.\n"; } } return 0;}
Output
输出量
Exception thrown. Currently, x = 0 caught.Default exception. Currently, i = -1 caught.Default exception. Currently, i = -2 caught.Default exception. Currently, i = -3 caught.
As you can see, initially, when i = 0
, it goes to the first catch
block, since we return an integer.
如您所见,最初,当i = 0
,它会转到第一个catch
块,因为我们返回一个整数。
But, after that, since we return the string “Default String”, it does not match with the first block, and it goes to the default block.
但是,此后,由于我们返回字符串“ Default String”,因此它与第一个块不匹配,并且转到了默认块。
Unfortunately, C++ does not give us a way to pass the object in the default case, so we cannot get the “Default String” string. This shows that we must use this only for adding functionality to our code, to account for unknown errors.
不幸的是,C ++没有提供在默认情况下传递对象的方法,因此我们无法获取“ Default String”字符串。 这表明我们只能将其用于为代码添加功能,以解决未知错误。
This is also possible since we’re working with C++!
由于我们正在使用C ++,因此这也是可能的!
A general rule is to handle all the freeing related to the pointers in the exception handling code.
一般规则是处理异常处理代码中与指针相关的所有释放。
try { call_function(base_ptr);}// Catch the Custom Exception Pointer using our Exception Classcatch(MyException* ex_obj) { delete ex_obj;}// Catch the reference to an Exception Class objectcatch(MyException& ex_obj) { // Do stuff ...}
Let’s consider the below exception handler class MyException
.
让我们考虑下面的异常处理程序类MyException
。
#include#include class MyException { public: int err; // Error Code std::string err_msg; // String containing Error Message MyException(int val = 0) { // Base Constructor err = val; switch(val) { case(-1): err_msg = "Case -1"; break; case(-2): err_msg = "Case -2"; break; case(-3): err_msg = "Case -3"; break; default: err_msg = "\0"; // No error message for other cases } } ~MyException() { std::cout << "Destructor for Exception Class called\n"; }};void function_call(int& x) { // Do some work, and modify the value of x, so we're passing by reference if (x <= 0) { // Throw an exception, and pass on the object x MyException* ex = new MyException(x); throw ex; // Throw the exception pointer } else { x = 100; }}int main() { for (int i=0; i>=-3; i--) { try { function_call(i); std::cout << "If this line executes, then x != 0\n"; } catch(MyException* ex) { std::cout << "Exception thrown. Error Message: " << ex->err_msg << "\n"; // Remember to free the pointer to the Exception!!! delete ex; } catch(...) { std::cout << "Default exception. Currently, i = " << i << " caught.\n"; } } return 0;}
Instead of passing on the integer directly, we construct an exception class and pass a pointer to an object, which has the relevant error code and error message.
与其直接传递整数,不如构造一个异常类,然后将一个指针传递给一个对象,该对象具有相关的错误代码和错误消息。
Here, you can see how powerful using an Exception Class handler for this is!
在这里,您可以看到使用Exception Class处理程序的强大功能!
Not only can we add debug messages to it, in the constructor, but when we actually pass it around, we only move the pointer, which is 8 bytes only! This is something other languages like Java can’t do easily.
我们不仅可以在构造函数中向其添加调试消息,而且在实际传递该消息时,我们仅移动了仅8个字节的指针! 这是其他语言(例如Java)无法轻松完成的。
Output
输出量
Exception thrown. Error Message: Destructor for Exception Class calledException thrown. Error Message: Case -1Destructor for Exception Class calledException thrown. Error Message: Case -2Destructor for Exception Class calledException thrown. Error Message: Case -3Destructor for Exception Class called
Indeed, this is what we expect! Only for values of -1, -2, and -3, we’ve instructed the constructor to set error messages. For other values, it is simply a NULL
string.
确实,这就是我们的期望! 仅针对值-1,-2和-3,我们指示构造函数设置错误消息。 对于其他值,它只是一个NULL
字符串。
try
and catch
blocks, there is NO implicit type conversion taking place. So a char
is not converted to an int
, when passed to exception handlers. 当使用try
和catch
块, 不存在隐式类型转换的发生。 因此,当将char
传递给异常处理程序时,不会将其转换为int
。 catch
block if you use a try
block. Otherwise, if you throw an exception, this will result in an abnormal termination of the program. 如果使用try
块,请始终使用catch
块。 否则,如果引发异常,则将导致程序异常终止。 catch
blocks! If you find raw points too troublesome, use instead! 如果您使用原始指针,请始终记住在catch
块中释放它们! 如果发现原始点太麻烦,请改用 ! I hope you found this article useful for learning more about Exception Handling in C++. If you have any doubts, or even found any mistakes, please do mention them in the comment section below!
我希望您发现本文对了解C ++中的异常处理有用。 如果您有任何疑问,甚至发现任何错误,请在下面的评论部分中提及它们!
翻译自:
c ++异常处理
转载地址:http://kwlzd.baihongyu.com/