Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

UPDATED CODE TO LET EXCEPTION BUBBLE:

public class DbConn {

    public Connection getConn() throws SQLException {
        Connection conn;
        String hostname = "localhost";
        String username = "root";
        String password = "root";

        Class.forName("com.mysql.jdbc.Driver").newInstance();
        if(System.getenv("MY_ENVIRONMENT") != "development") {
            hostname = "localhost";
            username = "produser";
            password = "prodpass";
        }
        conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
        return conn;

    }

}
like image 487
James Avatar asked May 31 '10 19:05

James


People also ask

How do you return an exception in Java?

You can throw an exception in Java by using the throw keyword. This action will cause an exception to be raised and will require the calling method to catch the exception or throw the exception to the next level in the call stack.

Can an exception be a return type?

Exceptions shouldn't be returned as a return value or parameter instead of being thrown. Don't throw System. Exception, System. SystemException, System.

What does a method return if it throws an exception?

Your method doesn't return at all. It always throws an exception. So you can specify any return type you want. Any code that calls your method won't be able to get a return value out of it anyway.

Can you throw an exception and return a value?

It's not possible to both throw an exception and return a value from a single function call. Perhaps it does something like returning false if there's an error, but throwing an exception if the input is invalid.


2 Answers

If an exception is thrown, there is no normal value returned from the method. Usually the compiler is able to detect this, so it does not even pester you with "return required" style warnings/errors. Sometimes, when it is not able to do so, you need to give an "alibi" return statement, which will in fact never get executed.

Redefining your method like this

public Connection getConn() {
    Connection conn = null;
    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);
    } catch(Exception e) {
        // handle the exception in a meaningful way - do not just rethrow it!
    }
    return conn;
}

will satisfy Eclipse :-)

Update: As others have pointed out, re-throwing an exception in a catch block the way you did is not a good idea. The only situation when it is a decent solution is if you need to convert between different exception types. E.g. a method called throws an exception type which you can not or do not want to propagate upwards (e.g. because it belongs to a proprietary library or framework and you want to isolate the rest of your code from it).

Even then, the proper way to rethrow an exception is to pass the original exception into the new one's constructor (standard Java exceptions and most framework specific exceptions allow this). This way the stack trace and any other information within the original exception is retained. It is also a good idea to log the error before rethrowing. E.g.

public void doSomething() throws MyException {
    try {
        // code which may throw HibernateException
    } catch (HibernateException e) {
        logger.log("Caught HibernateException", e);
        throw new MyException("Caught HibernateException", e);
    }
}
like image 166
Péter Török Avatar answered Oct 26 '22 04:10

Péter Török


You should just eliminate your entire try/catch block and allow exceptions to propagate, with an appropriate exception declaration. This will eliminate the error that Eclipse is reporting, plus right now your code is doing something very bad: by catching and re-throwing all exceptions, you're destroying the original stack trace and hiding other information contained in the original exception object.

Plus, what is the purpose of the line Class.forName("com.mysql.jdbc.Driver").newInstance();? You're creating a new mysql Driver object through reflection (why?) but you're not doing anything with it (why?).

like image 43
JSBձոգչ Avatar answered Oct 26 '22 03:10

JSBձոգչ