我正在开发一个小型 c++ 程序并学习异常。下面的代码是否“不好”,如果是,我可以做些什么来改进它?
try {
// code
if (some error) {
throw "Description of error.";
}
}
catch (char* errorMessage) {
cerr << errorMessage << endl << "Fatal error";
}
将 char
数组作为异常抛出有什么问题吗?
编辑: 这会是更好的方法吗?
const char errorMessage[] = "Description of error";
try {
// code
if (some error) {
throw errorMessage;
}
}
catch (char* errorMessage) {
cerr << errorMessage << endl << "Fatal error";
}
最佳答案
抛出一个标准的异常对象要好得多。一般来说,最好的做法是抛出一些从 std::exception
派生的东西,这样如果在某些情况下它确实导致你的程序终止,实现就有更好的机会打印有用的诊断信息。
因为这样做并不难,所以我绝不建议抛出原始字符串文字。
#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;
}
}
https://stackoverflow.com/questions/6248404/