【问题标题】:Java exception thrown in a "try" block cannot get caught outside of the "try...catch"在“try”块中抛出的 Java 异常不能在“try...catch”之外被捕获
【发布时间】:2020-03-20 20:04:47
【问题描述】:

我正在使用我自己的个性化 java 异常 DaoException(继承自 java.lang.Exception),我在方法内的 try 块内抛出该异常。问题是虽然我只捕获了其他类型的异常(例如 java.sql.SQLException),但似乎 DaoException 也无法超出该块。当我在其他地方使用我的方法时,我无法捕获我的 DaoException,就好像它从未被抛出一样。

我没有编译或执行错误,所以我很困惑,特别是因为当我将我的 DaoException 抛出 try 块之外时,它可以正常工作。

我找不到遇到同样问题的人,所以我真的希望在这里找到一些帮助。

这是我的方法的结构:

public Member getById(int id) throws DaoException
{
    ...
    try
    {
        ...
        if (id<0){
           throw new DaoException("Indice de membre invalide");}
        ...
    }
    catch(SQLException e)
    {
        throw new DaoException("[SQLException]"+e.getLocalizedMessage());   
    }
    finally
    {
        return member;
    }
}

这是我的 DaoException,这是非常基本的:

public class DaoException extends Exception
{
    public DaoException(String message)
    {
        super(message);
    }
}

【问题讨论】:

标签: java exception try-catch


【解决方案1】:

您的finally 块中有返回值。这意味着您将在异常发生时将其丢弃,以便您可以返回。

如果您希望异常继续存在,请不要在 finally 块中返回。

【讨论】:

  • 谢谢,如果我将return 移到finally 块之外,它会起作用!我不知道return语句是优先于抛出的,但它实际上是很合乎逻辑的:)
猜你喜欢
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 2011-03-25
  • 1970-01-01
相关资源
最近更新 更多