0

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
        }
    }
kandarp
  • 991
  • 1
  • 14
  • 35
  • 1
    Have you already seen this https://stackoverflow.com/questions/27280928/how-to-check-which-exception-type-was-thrown-in-java/51538776 ? – Dani Jun 01 '21 at 11:58

1 Answers1

6

Maybe you need this:

String stringEx = "org.hibernate.StaleStateException";
try {
    // program
} catch (Exception ex) {
    if (Class.forName(stringEx).isInstance(ex)) { 
        // do specific process
    }
}
Sergey Afinogenov
  • 2,137
  • 4
  • 13