C ++异常 - 是否抛出c字符串作为异常? [英] C++ Exceptions - Is throwing c-string as an exception bad?
问题描述
我正在开发一个小型的c ++程序和学习异常。下面的代码是否坏,如果是,我该怎么做才能改善呢?
I am working on a small c++ program and learning exceptions. Is the following code "bad", and if so, what can I do to improve it?
try {
// code
if (some error) {
throw "Description of error.";
}
}
catch (char* errorMessage) {
cerr << errorMessage << endl << "Fatal error";
}
抛出 code>数组作为例外?
Is there anything wrong with throwing a char
array as an exception?
编辑:
这将是一个更好的方式吗?
Would this be a better way to go?
const char errorMessage[] = "Description of error";
try {
// code
if (some error) {
throw errorMessage;
}
}
catch (char* errorMessage) {
cerr << errorMessage << endl << "Fatal error";
}
推荐答案
一个标准异常对象。一般来说,最佳实践是抛出从 std :: exception
派生的东西,这样,如果在某些情况下它确实导致你的程序终止,实现有更好的机会打印一个有用的诊断。
It is much better to throw a standard exception object. In general, the best practice is to throw something derived from std::exception
so that if in some situation it does cause your program to terminate, the implementation has a better chance of printing a useful diagnostic.
因为这不难做,我不会建议抛出一个原始的字符串文字。
Because it isn't hard to do this, I would never recommend throwing a raw string literal.
#include <stdexcept>
void someFunction()
{
try {
// code
if (some error) {
throw std::runtime_error( "Description of error." );
}
}
catch (const std::exception& ex) {
std::cerr << ex.what() << "\nFatal error" << std::endl;
}
}
这篇关于C ++异常 - 是否抛出c字符串作为异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!