kandarp
kandarp

Reputation: 1111

How to get Exception Class from Exception Name

I have a string variable that has a full qualified exception name. I want to check in catch block if exceptions occur whether it is an instance of exception that mentioned in string or not. How to solve that

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

Upvotes: 0

Views: 214

Answers (1)

Sergey Afinogenov
Sergey Afinogenov

Reputation: 2222

Maybe you need this:

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

Upvotes: 6

Related Questions