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?
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
精彩评论