Link to home
Create AccountLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

When do we rethrow exception in catch block with different exception

Hi,

When do we rethrow exception in catch block with different exception?

Say


class ExceptionClass
{
public static void main(String[] args){
try {
System.out.println(9/0);
}
catch(ArithmeticException e) {
throw new NullPointerException();
}
}
}

I wonder whether we can do like above and in what situations we do like above?
please advise
ASKER CERTIFIED SOLUTION
Avatar of gurpsbassi
gurpsbassi
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of gudii9

ASKER

Any simple example on this?
exactly what I said:

public void doSomethingDangerous() throws DataAccessException{

    try{
            ...something that can cause a SQLException
         }catch(SQLException e){
          throw new DataAccessException(e);
        }

}
Avatar of gudii9

ASKER

What's dataaccessexceptiob?I never heard? Is it custom exception?
Ok, lets call it Guddi9Exception.
Avatar of gudii9

ASKER

If you have a method that declares a data access exception for example in its throws clause.

If the body of the method catches a SQLException, you will probably want to wrap that in data access exception before throwing it out to the caller. You would not want the caller to handle SQLException.

we would want caller to handle data access exception instead right?
Yes. The caller may decide the handle it or let it bubble up the call stack and simply do nothing