1. 定义头文件 CustomException.h
#pragma once
#include <exception>
#include <QString>
class CustomException : public std::exception {
public:
CustomException(const QString& message, const char* file, int line,
const char* function)
: message_(message), file_(file), line_(line), function_(function) {}
const char* what() const noexcept override {
return message_.toStdString().c_str();
}
QString getMessage() const {
return message_;
}
const char* getFile() const {
return file_;
}
int getLine() const {
return line_;
}
const char* getFunction() const {
return function_;
}
private:
QString message_;
const char* file_;
int line_;
const char* function_;
};
//为了方便抛出异常,可以定义一个宏来捕获文件名、行号和函数名
#define THROW_CUSTOM_EXCEPTION(message) throw CustomException((message), __FILE__, __LINE__, __func__)
2. 主程序文件 main.cpp
#include <QApplication>
#include <QMessageBox>
#include "CustomException.h"
// 一个示例函数,抛出 CustomException 异常
void exampleFunction() {
// 某些条件下抛出异常
bool errorCondition = true;
if (errorCondition) {
THROW_CUSTOM_EXCEPTION("An error occurred in exampleFunction!");
}
}
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
try {
// 调用可能抛出异常的函数
exampleFunction();
} catch (const CustomException& e) {
// 捕获并处理自定义异常
QString errorMessage = QString("Error: %1\nFile: %2\nLine: %3\nFunction: %4")
.arg(e.getMessage())
.arg(e.getFile())
.arg(e.getLine())
.arg(e.getFunction());
// 显示错误信息的消息框
QMessageBox::critical(nullptr, "Exception Caught", errorMessage);
// 中止程序
return EXIT_FAILURE;
}
return app.exec();
}