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

后端 未结 6 1072
[愿得一人]
[愿得一人] 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:16

    Never, ever, ever use a generic exception like that. If you don't have a ready made exception (in this case, an SQLException), make your own exception type and throw it. Every time I encounter something that declares that it "throws Exception", and it turns out that it does so because something it calls declares "throws Exception", and so on down the line, I want to strangle the idiot who started that chain of declarations.

    0 讨论(0)
  • 2021-02-14 11:17

    I'm sorry, but you shouldn't be writing code like this, even if you're new to Java.

    If you must write such a thing, I'd make it more like this:

    public class DatabaseUtils 
    {
    
        public static Connection getConnection(String driver, String url, String username, String password) throws SQLException 
        {
            Class.forName(driver).newInstance();
    
    
            return DriverManager.getConnection(url, username, password);
        }
    }
    

    And you should also be aware that connection pools are the true way to go for anything other than a simple, single threaded application.

    0 讨论(0)
  • 2021-02-14 11:19

    This is exactly the situation where you should let the exception propagate up the call stack (declaring the method as throws SQLException or wrapping it in a application-specific exception) so that you can catch and handle it at a higher level.

    That's the whole point of exceptions: you can choose where to catch them.

    0 讨论(0)
  • 2021-02-14 11:20

    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?).

    0 讨论(0)
  • 2021-02-14 11:22

    Try this one

    public ActionForward Login(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        MigForm migForm = (MigForm) form;// TODO Auto-generated method stub
    
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
    
        String uname=migForm.getUname();
        String pwd=migForm.getPwd();
    
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","uname","pwd");
            if(con.isClosed())
            {
                return mapping.findForward("success");
            }
    
            //st=con.createStatement();
    
            }catch(Exception err){
    
            System.out.println(err.getMessage());
            }
    
    
                return mapping.findForward("failure");
    
    
    
    }
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题