14.2 异常体系
14.1 的日志记录「发生了什么」;这一节讲「出错了怎么爆出来」。OGRE 的契约很明确——永不靠返回值报错。OgreException.h 的类注释开宗明义:发生错误就抛异常,应用必须用 try{} catch(Ogre::Exception& e) {} 包住引擎调用。这一节拆 Exception、错误码枚举和 ExceptionFactory 的分发逻辑。
本章与站内既有内容的分工
站内 java-conc-juc 系列也讲语言级异常机制,但那是 JVM 语义;OGRE 是 C++ 引擎自定义异常体系——基类字段、错误码枚举、码→类型分发三件套,是引擎内部「错误报告协议」的设计范本。
Exception:错误码 + 描述 + 出处
Exception 直接继承 std::exception,因此可以被 catch(std::exception&) 捕获,what() 返回完整描述:
// OgreMain/include/OgreException.h:class Exception(v14.6.3 源码摘录,已删减)
class _OgreExport Exception : public std::exception
{
protected:
long line;
const char* typeName;
String description;
String source;
const char* file;
String fullDesc; // storage for char* returned by what()
public:
/** Static definitions of error codes.
@todo
Add many more exception codes, since we want the user to be able
to catch most of them.
*/
enum ExceptionCodes {
ERR_CANNOT_WRITE_TO_FILE,
ERR_INVALID_STATE,
ERR_INVALIDPARAMS,
ERR_RENDERINGAPI_ERROR,
ERR_DUPLICATE_ITEM,
ERR_ITEM_NOT_FOUND = ERR_DUPLICATE_ITEM,
ERR_FILE_NOT_FOUND,
ERR_INTERNAL_ERROR,
ERR_RT_ASSERTION_FAILED,
ERR_NOT_IMPLEMENTED,
ERR_INVALID_CALL
};
const String& getFullDescription(void) const { return fullDesc; }
/** Gets the source function.
*/
const String &getSource() const { return source; }
/** Gets source file name.
*/
const char* getFile() const { return file; }
/** Gets line number.
*/
long getLine() const { return line; }
/** Returns a string with only the 'description' field of this exception.
*/
const String &getDescription(void) const { return description; }
const char* what() const throw() override { return fullDesc.c_str(); }
};
六个字段各司其职:line/file 指出源码位置,source 是抛出函数名,description 是给人看的具体描述,typeName 记类型名,fullDesc 缓存 what() 的完整字符串。访问器只读,构造后不可变。
注意错误码枚举里的一个设计细节:ERR_ITEM_NOT_FOUND = ERR_DUPLICATE_ITEM——「重复项」和「找不到项」共享同一个数值。原因是历史演进:早期把「取不到」记成 DUPLICATE,后来语义拆分但不想破坏既有捕获代码,于是二者等价。捕获 ERR_DUPLICATE_ITEM 的代码同时也能捕到「找不到」。这在 API 兼容上很实用,但读代码时要记住这个别名。
具体派生异常:每码一个类型
Exception 之下是一串一一对应的派生类,每个都带 _OgreExport 并转发到高级构造:
// OgreMain/include/OgreException.h:派生异常(v14.6.3 教学示意,参照上游同名实现,已删减)
class _OgreExport UnimplementedException : public Exception
{
public:
UnimplementedException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine)
: Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {}
};
class _OgreExport FileNotFoundException : public Exception
{
public:
FileNotFoundException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine)
: Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {}
};
class _OgreExport IOException : public Exception { ... };
class _OgreExport InvalidStateException : public Exception { ... };
class _OgreExport InvalidParametersException : public Exception { ... };
class _OgreExport ItemIdentityException : public Exception { ... };
class _OgreExport InternalErrorException : public Exception { ... };
class _OgreExport RenderingAPIException : public Exception { ... };
class _OgreExport RuntimeAssertionException : public Exception { ... };
class _OgreExport InvalidCallException : public Exception { ... };
一个细节:构造时把 __FUNCTION__ 作为 type 传给基类——类型名是编译器自动填的,派生类本身不写死字符串。好处是重命名类时 typeName 自动跟随,不会出现「类改了名、日志里还是旧名」的漂移。
这样设计让应用可以用多种粒度捕获:catch(FileNotFoundException&) 精确处理文件缺失,catch(RenderingAPIException&) 处理显卡驱动层错误,兜底 catch(Exception&) 收住一切。
ExceptionFactory:错误码 → 具体类型
OGRE_EXCEPT 只传错误码,具体抛什么类型由 ExceptionFactory::_throwException 的 switch 决定:
// OgreMain/include/OgreException.h:ExceptionFactory(v14.6.3 源码摘录,已删减)
class ExceptionFactory
{
private:
/// Private constructor, no construction
ExceptionFactory() {}
static OGRE_NORETURN void _throwException(
Exception::ExceptionCodes code, int number,
const String& desc,
const String& src, const char* file, long line)
{
switch (code)
{
case Exception::ERR_CANNOT_WRITE_TO_FILE: throw IOException(number, desc, src, file, line);
case Exception::ERR_INVALID_STATE: throw InvalidStateException(number, desc, src, file, line);
case Exception::ERR_INVALIDPARAMS: throw InvalidParametersException(number, desc, src, file, line);
case Exception::ERR_RENDERINGAPI_ERROR: throw RenderingAPIException(number, desc, src, file, line);
case Exception::ERR_DUPLICATE_ITEM: throw ItemIdentityException(number, desc, src, file, line);
case Exception::ERR_FILE_NOT_FOUND: throw FileNotFoundException(number, desc, src, file, line);
case Exception::ERR_INTERNAL_ERROR: throw InternalErrorException(number, desc, src, file, line);
case Exception::ERR_RT_ASSERTION_FAILED: throw RuntimeAssertionException(number, desc, src, file, line);
case Exception::ERR_NOT_IMPLEMENTED: throw UnimplementedException(number, desc, src, file, line);
case Exception::ERR_INVALID_CALL: throw InvalidCallException(number, desc, src, file, line);
default: throw Exception(number, desc, src, "Exception", file, line);
}
}
public:
static OGRE_NORETURN void throwException(
Exception::ExceptionCodes code,
const String& desc,
const String& src, const char* file, long line)
{
_throwException(code, code, desc, src, file, line);
}
};
十一个码全部映射到具体类型,default 兜底抛裸 Exception。类注释说明这样做的动机:「按值构造派生异常又不产生歧义」——每个码对应一个独立类型,_throwException 靠重载/switch 完成码→类型映射,OGRE_EXCEPT 宏本身保持极简。OGRE_NORETURN 让编译器知道这个函数必抛,从而允许「if 失败就调它」的模式而无警告。
OGRE_EXCEPT:宏补全出处
throwException 需要 src/file/line,手写很啰嗦,所以有宏自动填入:
// OgreMain/include/OgreException.h:OGRE_EXCEPT 宏(v14.6.3 源码摘录,已删减)
#ifndef OGRE_EXCEPT
#define OGRE_EXCEPT_3(code, desc, src) Ogre::ExceptionFactory::throwException(code, desc, src, __FILE__, __LINE__)
#define OGRE_EXCEPT_2(code, desc) Ogre::ExceptionFactory::throwException(code, desc, __FUNCTION__, __FILE__, __LINE__)
#define OGRE_EXCEPT_CHOOSER(arg1, arg2, arg3, arg4, ...) arg4
#define OGRE_EXPAND(x) x // MSVC workaround
#define OGRE_EXCEPT(...) OGRE_EXPAND(OGRE_EXCEPT_CHOOSER(__VA_ARGS__, OGRE_EXCEPT_3, OGRE_EXCEPT_2)(__VA_ARGS__))
#endif
两个版本:OGRE_EXCEPT(code, desc) 用 __FUNCTION__ 作来源,OGRE_EXCEPT_3(code, desc, src) 用调用者显式给的来源。CHOOSER 是经典的参数数量分派——根据参数个数展开成 _3 或 _2。__FILE__/__LINE__ 由预处理器填入,异常里永远带着真实的抛出位置。
从错误码定位故障层
文件定位、Codec 选择与格式解析在不同调用层失败。记录异常类型和 source,结合资源名、组和文件位置,才能区分归档未命中、没有 Codec 和版本无法分派。
同一个缺失网格在原生样例中由 worker 的 prepare 抛出,future.get 在调用方重新呈现异常。主线程 load 阶段的异常沿任务处理路径观察。
源码定位
OgreMain/include/OgreException.h:class Exception、enum ExceptionCodes、各派生异常、ExceptionFactory::_throwException、OGRE_EXCEPT宏
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现 Exception 字段、错误码别名与工厂分发。它与 src/14-2-exception-hierarchy.cpp 逐字节一致:
// file: src/14-2-exception-hierarchy.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/14-2-exception-hierarchy.cpp -o bin/14-2-exception-hierarchy && ./bin/14-2-exception-hierarchy
//
// 复现 OGRE 异常体系:
// Exception : public std::exception,含错误码 + 描述 + 来源函数 + 文件行号;
// ExceptionCodes 枚举(ERR_INVALIDPARAMS / ERR_DUPLICATE_ITEM /
// ERR_ITEM_NOT_FOUND = ERR_DUPLICATE_ITEM / ERR_FILE_NOT_FOUND / ERR_INTERNAL_ERROR);
// ExceptionFactory 按错误码抛派生的具体异常(对应 OgreException.h 的 switch);
// 捕获方既可 catch 派生异常,也可 catch 基类 Exception。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <string>
namespace ogre_repro {
// 对应 Ogre::Exception 的简化基类
class Exception {
public:
enum ExceptionCodes {
ERR_INVALIDPARAMS,
ERR_DUPLICATE_ITEM,
ERR_ITEM_NOT_FOUND = ERR_DUPLICATE_ITEM,
ERR_FILE_NOT_FOUND,
ERR_INTERNAL_ERROR,
};
Exception(int number, const std::string& description, const std::string& source,
const char* file, long line)
: mNumber(number), mDescription(description), mSource(source), mFile(file), mLine(line) {
mFullDesc = "OGRE EXCEPTION(" + std::to_string(number) + ": " + description +
") in " + source + " at " + file + ":" + std::to_string(line);
}
int getNumber() const { return mNumber; }
const std::string& getDescription() const { return mDescription; }
const std::string& getSource() const { return mSource; }
long getLine() const { return mLine; }
const std::string& getFullDescription() const { return mFullDesc; }
int mNumber;
std::string mDescription;
std::string mSource;
const char* mFile;
long mLine;
std::string mFullDesc;
};
// 派生异常(对应 OgreException.h 的 InvalidParametersException 等)
struct InvalidParametersException : public Exception {
InvalidParametersException(int n, const std::string& d, const std::string& s,
const char* f, long l) : Exception(n, d, s, f, l) {}
};
struct ItemIdentityException : public Exception {
ItemIdentityException(int n, const std::string& d, const std::string& s,
const char* f, long l) : Exception(n, d, s, f, l) {}
};
struct FileNotFoundException : public Exception {
FileNotFoundException(int n, const std::string& d, const std::string& s,
const char* f, long l) : Exception(n, d, s, f, l) {}
};
struct InternalErrorException : public Exception {
InternalErrorException(int n, const std::string& d, const std::string& s,
const char* f, long l) : Exception(n, d, s, f, l) {}
};
// 对应 ExceptionFactory:按错误码抛具体异常
class ExceptionFactory {
public:
static void throwException(int code, const std::string& desc, const std::string& src,
const char* file, long line) {
switch (code) {
case Exception::ERR_INVALIDPARAMS:
throw InvalidParametersException(code, desc, src, file, line);
case Exception::ERR_DUPLICATE_ITEM:
throw ItemIdentityException(code, desc, src, file, line);
case Exception::ERR_FILE_NOT_FOUND:
throw FileNotFoundException(code, desc, src, file, line);
case Exception::ERR_INTERNAL_ERROR:
throw InternalErrorException(code, desc, src, file, line);
default:
throw Exception(code, desc, src, file, line);
}
}
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// ERR_INVALIDPARAMS → InvalidParametersException
bool caught = false;
try {
ExceptionFactory::throwException(Exception::ERR_INVALIDPARAMS,
"bad value", "SomeClass::foo", __FILE__, __LINE__);
} catch (const InvalidParametersException& e) {
caught = true;
CHECK(e.getNumber() == Exception::ERR_INVALIDPARAMS);
CHECK(e.getDescription() == "bad value");
CHECK(e.getSource() == "SomeClass::foo");
CHECK(e.getFullDescription().find("OGRE EXCEPTION") != std::string::npos);
}
CHECK(caught);
// ERR_ITEM_NOT_FOUND == ERR_DUPLICATE_ITEM(同一错误码)
CHECK(Exception::ERR_ITEM_NOT_FOUND == Exception::ERR_DUPLICATE_ITEM);
// 按错误码 catch:ERR_DUPLICATE_ITEM → ItemIdentityException
caught = false;
try {
ExceptionFactory::throwException(Exception::ERR_DUPLICATE_ITEM,
"duplicate", "SomeClass::foo", __FILE__, __LINE__);
} catch (const ItemIdentityException& e) {
caught = true;
CHECK(e.getNumber() == Exception::ERR_DUPLICATE_ITEM);
}
CHECK(caught);
// 派生异常都能按基类 Exception 捕获(共性信息:行号来自抛出点)
caught = false;
const long throwLine = __LINE__;
try {
ExceptionFactory::throwException(Exception::ERR_FILE_NOT_FOUND,
"missing.mesh", "load", __FILE__, throwLine);
} catch (const Exception& e) {
caught = true;
CHECK(e.getLine() == throwLine);
}
CHECK(caught);
return lab::report("14-2 日志与异常:异常体系");
}
本机实测(Apple clang 16,clang++ -std=c++20):编译通过(-Wall 零警告),断言 10/10 通过。
小结
- OGRE 的契约是永不靠返回值报错,一切错误走
Exception异常。 Exception携带错误码、描述、来源函数、文件名与行号,what()返回完整描述。ExceptionCodes有别名:ERR_ITEM_NOT_FOUND = ERR_DUPLICATE_ITEM,历史语义共享一个数值。ExceptionFactory::_throwException用 switch 把错误码映射到具体派生异常,default兜底裸Exception。OGRE_EXCEPT宏靠参数数量分派自动补__FUNCTION__/__FILE__/__LINE__。
阅读导航:上一节:14.1 日志管理器 · 下一节:14.3 LogManager 单例与监听 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。