简体   繁体   English

C ++中的通用异常处理

[英]Generic exception handling in C++

In python you can use: 在python中,您可以使用:

try:
    #some code
except Exception as e:
    print e

And this will automatically catch any exception. 这将自动捕获任何异常。 Lets say you want to make a simple division in '#some code" ... 假设您要在“ #some代码”中进行简单的划分...

variable = int(raw_input('Input: '))
result = 50/variable

Now, imagine somebody enters 0, or a letter, or even a string... As far as I know, since we used the generic exception catch, all of this will be taken care of and thus the code will jump to the except block, avoiding a crash. 现在,假设有人输入了0,或者是一个字母,甚至是一个字符串……据我所知,由于我们使用了通用异常捕获,因此所有这些都将得到处理,因此代码将跳转到except块,避免崩溃。


In C++, you would have to check that the input is a number in one IF statement, and then check that it is not zero in another one, and if that's the case, throw the corresponding exception/s. 在C ++中,必须在一个IF语句中检查输入是否为数字,然后在另一个IF语句中检查输入是否为零,如果是这种情况,请抛出相应的异常。

int var = 0, result = 0;

try{
    cin >> var;

    if (var == 0)
        throw "Zero Division Error";

    result = 50/var;

}catch(...){
    //exception handling code
}

All of this, (although untidy, and a bad practice), could have been done simply with pure IF-ELSE statements, without the try-catch block. 所有这些(尽管不整洁,也是一种不好的做法),本来可以仅使用纯IF-ELSE语句来完成,而无需使用try-catch块。 However, in C++, should any unexpected exception occur, you are done. 但是,在C ++中,如果发生任何意外的异常,您就可以完成。 You have to manually take care of every exception, adding throw statements for every possible case, whereas in python, this is done automatically for you, and it even tells you what went wrong, and what kind of exception your generic variable 'e' caught. 您必须手动处理每个异常,为每种可能的情况添加throw语句,而在python中,这是自动为您完成的,甚至可以告诉您出了什么问题以及您的通用变量'e'捕获了哪种异常。


So the question is: 所以问题是:
Is there a way to write a try-catch block in whatever version of C++, that automatically takes care of any exception and assign it to a generic variable for you to print? 有没有一种方法可以在任何版本的C ++中编写try-catch块,该块可以自动处理任何异常并将其分配给通用变量以供您打印?

Because if there is not, I don't see the purpose of using the try-catch structure, other than making your code look tidy and more organized (same with the switch statement). 因为如果没有,我看不到使用try-catch结构的目的,除了使您的代码看起来更整洁和更有条理(与switch语句相同)之外。

Is there a way to write a try-catch block in whatever version of C++, that automatically takes care of any exception and assign it to a generic variable for you to print? 有没有一种方法可以在任何版本的C ++中编写try-catch块,该块可以自动处理任何异常并将其分配给通用变量以供您打印?

Yes if you follow the practice of only throwing exceptions of class type derived publicly from std::exception and overridding the what() method so that it returns a string with some appropriate error message. 是的, 如果您遵循只抛出从std::exception公开派生的类类型的std::exception并覆盖what()方法的做法,那么该方法将返回带有一些适当错误消息的字符串。 Any exception can then be handled with: 然后可以使用以下方法处理任何异常:

try {
    // ...
} catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}

For example, you could write an exception class like this: 例如,您可以编写如下这样的异常类:

class divide_error : public std::exception {
    const char* what() const {
        return "division by 0";
    }
};

The question of what exactly exceptions are good for in C++ is more opinion-based and has been covered elsewhere. 在C ++中,究竟什么是例外到底有什么好处的问题更多地基于观点,并且在其他地方已涉及。 See When and how should I use exception handling? 请参阅何时以及如何使用异常处理?

Regarding the fact that high level languages like python "automatically" detect exceptions, it all lies upon the fact that everything is an object (even simple ints and chars), and every operator is overloaded accordingly, so, for example, if you try to divide by zero, the interpreter (as opposed to C++'s compiler which simply does the appropriate bit wise operations, making it faster but more basic) takes the operation as a whole predefined method, and executes it accordingly. 对于像python这样的高级语言“自动”检测异常的事实,这一切都取决于所有事物都是一个对象(甚至是简单的ints和chars),并且每个运算符都会相应地重载,因此,例如,如果您尝试除以零后, 解释器 (与C ++的编译器仅执行适当的按位运算,从而使其更快但更基础)相对应,将运算作为一个完整的预定义方法,并相应地执行该方法。 The important thing is that Inside Those methods predefined by python itself, there already are all the required checks that raise the corresponding exceptions. 重要的是,在那些由python本身预定义的方法中,已经存在所有引发相应异常的必需检查。

If you take the time to overload everything and make sure that every variable you treat is actually an object, and all its methods and operators do the all corresponding checking, throwing a generic exception (that is making sure to define a default generic exception class, derived from the std::exception class, and overriding the corresponding methods to achieve your desired result, just like @Brian said) if necessary, you can achieve practically the same result. 如果您花时间重载所有内容,并确保您处理的每个变量实际上都是一个对象,并且其所有方法和运算符都进行所有相应的检查,则抛出泛型异常(即确保定义默认的泛型异常类,派生自std :: exception类,并覆盖相应的方法以实现所需的结果,就像@Brian所说的那样)(如果需要),实际上可以达到相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM