MarieKalouguine
MarieKalouguine

Reputation: 9

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

Upvotes: 0

Views: 756

Answers (1)

khelwood
khelwood

Reputation: 59229

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.

Upvotes: 4

Related Questions