Unreported exception java.sql.SQLException; must be caught or declared to be thrown?

前端 未结 4 1722
孤街浪徒
孤街浪徒 2020-11-30 13:46

I got this error while trying to compile the below code. I would like to know what is I have done wrong.

unreported exception java.sql.SQLException; must be caugh         


        
相关标签:
4条回答
  • 2020-11-30 14:32

    This line of code throws an uncaught exception:

    Driver driver = new org.gjt.mm.mysql.Driver();
    

    try this:

    try {
       Driver driver = new org.gjt.mm.mysql.Driver();
    }
    catch (java.sql.SQLException e) {
      // you may want to do something useful here
     // maybe even throw new RuntimException();
    }
    
    0 讨论(0)
  • 2020-11-30 14:36

    You either need to catch the exception in your method:

    public void setupInfo()
    {
        try
        {
            // call methods that might throw SQLException
        }
        catch (SQLException e)
        {
            // do something appropriate with the exception, *at least*:
            e.printStackTrace();
        }
    }
    

    Or declare the method to throw SQLException:

    private void setupInfo() throws SQLException
    {
        // call methods that might throw SQLException
    }
    
    0 讨论(0)
  • 2020-11-30 14:41

    Always try to get help from your IDE. IDEs can often fix the error automatically. Press alt+enter in IntelliJ IDEA or ctrl+1 in Eclipse and choose to fix the error.

    0 讨论(0)
  • 2020-11-30 14:42

    Catch the exception or throw it. Better use an IDE (Eclipse or Netbeans), which will tell you the error the moment you press enter.

    0 讨论(0)
提交回复
热议问题