在Java中,如果发生异常,如何设置返回类型? [英] In Java, how do I set a return type if an exception occurs?

查看:310
本文介绍了在Java中,如果发生异常,如何设置返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,所有,我是新来的Java,并想知道我是否定义一个方法来返回数据库对象



  import java.sql。*; 

public class DbConn {

public Connection getConn(){
Connection conn;
尝试{
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());
}

}

}

如果连接失败,当我尝试创建它应该返回什么? eclipse告诉我我必须返回一个Connection对象,但如果它失败了,我不知道该怎么做。



谢谢!



更新的代码以免排除泡沫:

  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;

}

}


解决方案

如果抛出异常,则该方法没有返回正常值。通常,编译器能够检测到这种情况,所以甚至不会使用返回必需样式警告/错误。有时,如果不能这样做,你需要给出一个不在场的返回语句,实际上从来没有执行过。



重新定义你的方法

  public Connection getConn(){
Connection conn = null;
尝试{
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){
//以有意义的方式处理异常 - 不要只是推翻它!
}
return conn;
}

将满足Eclipse: - )



更新:正如其他人指出的那样,在catch块中重新抛出异常并不是一个好主意。唯一的情况,当它是一个体面的解决方案是如果你需要转换不同的异常类型。例如。一种叫做抛出异常类型的方法,您不能或不想向上传播(例如,因为它属于专有库或框架,并且您想要将其余的代码与之隔离开)。即使这样,重新抛出异常的正确方法是将原始异常传递给新的构造函数(标准Java异常和大多数框架特定的异常允许这一点)。这样,保留堆栈跟踪和原始异常中的任何其他信息。在重新抛出之前记录错误也是一个好主意。例如

  public void doSomething()throws MyException {
try {
//可能会抛出HibernateException的代码
} catch(HibernateException e){
logger.log(Caught HibernateException,e);
抛出新的MyException(Caught HibernateException,e);
}
}


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;

    }

}

解决方案

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

这篇关于在Java中,如果发生异常,如何设置返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆