C++抛出异常学习笔记

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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值