0

I'm writing a simple JAVA GUI to read an SQL query from a JTextFrame and execute it.

The connect and execute buttons are both JButtons, but the compiler won't compile my code because I can't append a "throws SQLException" to actionPerformed in my Listener private classes. I tried writing separate methods, but the same problem still persists. Here's an example:

public void connect() throws SQLException {
    conxn = DriverManager.getConnection(URL, Username, Password);
}
private class SelectBut implements ActionListener {  
    public void actionPerformed(ActionEvent event){
        connect();
    }
}

The compiler just throws this back at me:

TextFrame.java:123: unreported exception java.sql.SQLException; must be caught or declared to be thrown  
public void actionPerformed(ActionEvent event){connect();}}

Any suggestions?

1
  • Catch it or declare it to be thrown, just as the error message tells you to. You’ll realize that you can not declare it to be thrown so I guess you have to catch it. Wow, that was hard. Commented Nov 24, 2009 at 11:49

1 Answer 1

3

Since SQLException are checked exception , you must re-throw or catch it.

in your case your actionPerformed method can be something like that :

public void actionPerformed(ActionEvent event){
    try{
         connect();
    }catch(SQLException e){
         e.printStackTrace();
     }
 }

Here a tutorial about Catching and Handling Exception

Sign up to request clarification or add additional context in comments.

3 Comments

Yep, any method that may throw an execption must be within a try/catch block or the method calling this method must re-throw it.
Since the actionPerformed method doesn't include a throws clause, you can't throw any checked exceptions in your implementation. You'll have to catch it.
For what it's worth, the exception shouldn't be silently absorbed like this (or converted to a runtime exception) - this is a call that's going to occur on the EDT, and bringing the EDT down isn't a good idea. At minimum, display a JOptionPane dialog box with the error message. Another point to make here: The database query will almost certainly be a long running task - running that on the EDT is a bad idea. I suggest that you do a bit more reading up on developing Swing apps (SwingWorker may be a good idea here)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.