Can't catch SQLSyntaxErrorException in Java using MyBatis

10,743

Your exception has been wrapped into another one. Catch that other exception and then analyze its cause. For example:

try {
   ....
} catch (PersistenceException e) {
  try { throw e.getCause(); }
  catch (SQLSyntaxException e) {
    // handle the exception
  }
}

If that is not satisfactory, you can probe the cause with instanceof instead:

try {
   ....
} catch (PersistenceException e) {
  final Throwable cause = e.getCause();
  if (cause instanceof SQLSyntaxException) {
    // handle the exception
  }
}
Share:
10,743
Metalhead89
Author by

Metalhead89

I am currently working as Java software developer for a health insurance service provider.

Updated on June 04, 2022

Comments

  • Metalhead89
    Metalhead89 almost 2 years

    I currently face the following problem:

    I have written a Java program that parses XML data and puts the data in a database. Because I use MyBatis, the database could be nearly every database already existing. I'll just show you a piece of code and then I will explain the problem.

    public void insert(SourceContent content){    
        SqlSession session = sqlSessionFactory.openSession();           
            try {
                session.insert("SourceDocument.insert", content);
                session.commit();
            }   catch (Exception e){
                e.printStackTrace();
            } finally {
                session.close();
            }           
        }
    

    This is my DAO class for calling the sql statements of the MyBatis mapper file. Inserting my content (which is an instance of an java bean) wors fine, if the mapping configuration of MyBatis was done correctly. But imagine, if I rename a table in my database, then the connection fails because the configuration is wrong. Now I want to catch the upcoming error. When i use the statement like above:

    catch (Exception e){
                e.printStackTrace();
            } 
    

    the programm prints the right exception: ### Cause: java.sql.SQLSyntaxErrorException: ORA-00942: Tabelle oder View nicht vorhanden But I dont want to catch all Exception, I just want to catch the SQLSyntaxErrorException, because I want to tell the user, that the his table in the database is not available. But I just cant catch any other exceptions except of the normal Exception like seen above. I hope I had made it out clearly. Can anyone help me please?