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

后端 未结 6 1027
[愿得一人]
[愿得一人] 2021-02-14 10:37

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          


        
6条回答
  •  有刺的猬
    2021-02-14 11:35

    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);
        }
    }
    

提交回复
热议问题