In Java, how do I set a return type if an exception occurs?

Posted by beagleguy on Stack Overflow See other posts from Stack Overflow or by beagleguy
Published on 2010-05-31T19:19:45Z Indexed on 2010/05/31 19:33 UTC
Read the original article Hit count: 182

Filed under:

hey all, I'm new to Java and was wondering if I define a method to return a database object

like

import java.sql.*;

public class DbConn {

    public Connection getConn() {
        Connection conn;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            if(System.getenv("MY_ENVIRONMENT") == "development") {
                String hostname = "localhost";
                String username = "root";
                String password = "root";
            }
            conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
            return conn;
        } catch(Exception e) {
            throw new Exception(e.getMessage());
        }

    }

}

if the connection fails when I try to create it what should I return? eclipse is telling me I have to return a Connection object but if it fails I'm not sure what to do.

thanks!

© Stack Overflow or respective owner

Related posts about java