简体   繁体   中英

Java exception thrown in a "try" block cannot get caught outside of the "try...catch"

I am using my own personalized java exception DaoException (inherited from java.lang.Exception) that I throw inside of a try block inside of a method. The problem is that though I only catch other types of exceptions (such as java.sql.SQLException), it seems that the DaoException cannot get outside of the block as well. When I use my method elsewhere, I cannot catch my DaoException, as if it never was thrown.

I have no compilation or execution errors, so I am quite confused, especially because when throwing my DaoException outside of the try block, it works normally.

I could not find anyone who had the same problem, so I really hope to find some help here.

Here is the structure of my method:

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

And here is my DaoException, which is quite basical:

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

You have a return in your finally block. That means you're throwing away the exception when it happens so that you can return instead.

If you want the exception to survive, don't return in the finally block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM