【问题标题】:return statement not working with try catch in DAO java spring返回语句不适用于DAO java spring中的try catch
【发布时间】:2011-07-20 03:31:16
【问题描述】:

我在userDAO中有这个功能

public List<Country> findAllCountries() {

         try {

                 Session session = sessionFactory.getCurrentSession();
                 Query query = session.createQuery("FROM  Country");
                 return  query.list();

         } catch (Exception e) {
                    System.out.println(e);
                }


        }

问题是 eclipse 给出错误,告诉我要么使用 void 作为回报,要么添加 return 语句,如果我删除 try catch 那么它可以工作

【问题讨论】:

    标签: java spring try-catch return


    【解决方案1】:

    我会这样写。我不知道你应该做什么来关闭你的会话或在 finally 块中清理。这会让 Eclipse 高兴:

    public List<Country> findAllCountries() 
    {    
        List<Country> countries = new ArrayList<Country>();
    
        try 
        {
            Session session = sessionFactory.getCurrentSession();
            Query query = session.createQuery("FROM  Country");
            countries = query.list();    
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    
        return countries;
    }
    

    【讨论】:

      【解决方案2】:

      你还需要从你的 catch 块中返回一些东西(或抛出一个异常):

      catch (Exception e) {
               System.out.println(e);
               return null;
      }
      
      catch (Exception e) {
               System.out.println(e);
               throw new RuntimeException("DAO failed", e);
      }
      

      否则会有一个没有return语句的方法通过的代码路径。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        • 2018-10-14
        • 2017-09-22
        • 2014-03-10
        • 1970-01-01
        • 2012-11-19
        • 2011-03-28
        相关资源
        最近更新 更多