【问题标题】:How to get Exception Class from Exception Name如何从异常名称中获取异常类
【发布时间】:2021-08-19 14:56:53
【问题描述】:

我有一个具有完全限定异常名称的字符串变量。如果发生异常,我想检查 catch 块是否是字符串中提到的异常实例。如何解决这个问题

     String stringEx = "org.hibernate.StaleStateException";
    try {
        // program
    } catch (Exception ex) {
        if (e instanceof stringEx) { //<-- How to convert string to exception class 
            // do specific process
        }
    }

【问题讨论】:

标签: java spring exception


【解决方案1】:

也许你需要这个:

String stringEx = "org.hibernate.StaleStateException";
try {
    // program
} catch (Exception ex) {
    if (Class.forName(stringEx).isInstance(ex)) { 
        // do specific process
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2017-05-08
    • 2013-08-13
    • 2020-03-24
    • 1970-01-01
    • 2011-07-27
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多