Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Nov 2002
    Posts
    180
    Thanks
    0
    Thanked 0 Times in 0 Posts

    exception in Java

    i have this code:
    Code:
    package mysql; 
    import java.sql.*; 
    
    public class Hello {
    	Connection connection; 
    	
    	private void displaySQLErrors(SQLException e) {
    		System.out.println("SQLException: " + e.getMessage()); 
    		System.out.println("SQLState: " + e.getSQLState()); 
    		System.out.println("VendorError: " + e.getErrorCode()); 
    	}
    	
    	public Hello() {
    		try {
    			Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    		}
    		catch(SQLException e) {
    			System.err.println("Unable to find and load driver"); 
    			System.exit(1); 
    		}
    	}
    	
    	public void connectToDB() {
    		try {
    			connection = DriverManager.getConnection("jdbc:mysql://localhost/accounts?user=&password="); 
    		}
    		catch(SQLException e) {
    			displaySQLErrors(e); 
    		}
    	}
    	
    	public void executeSQL() {
    		try {
    			Statement statement = connection.createStatement(); 
    			
    			ResultSet rs = statement.executeQuery("SELECT * FROM acc_acc"); 
    			
    			while(rs.next()) {
    				System.out.println(rs.getString(1)); 
    			}
    			
    			rs.close(); 
    			statement.close(); 
    			connection.close(); 
    		}
    		catch(SQLException e) {
    			displaySQLErrors(e); 
    		}
    	}
    	
    	public static void main(String[] args) {
    		Hello hello = new Hello(); 
    		
    		hello.connectToDB(); 
    		hello.executeSQL(); 
    	}
    }
    i have 3 errors after compiling, the first:
    C:\Program Files\Xinox Software\JCreator LE\MyProjects\Hello.java:15: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
    the second:
    C:\Program Files\Xinox Software\JCreator LE\MyProjects\Hello.java:15: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
    the third:
    C:\Program Files\Xinox Software\JCreator LE\MyProjects\Hello.java:17: exception java.sql.SQLException is never thrown in body of corresponding try statement
    why? and how can i solve it?

  • #2
    Regular Coder
    Join Date
    Dec 2003
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Class.forName() doesn't throw an SQLException, but it might throw a ClassNotFoundException if the class doesn't exist in it's classpath. So instead of catching an SQLException you should be catching a ClassNotFoundException (or something above it in the hierarchy like Exception).

    shmoove


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •