When do we rethrow exception in catch block with different exception

gudii9
gudii9 used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2015
Commented:
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.

Author

Commented:
Any simple example on this?
Top Expert 2015

Commented:
exactly what I said:

public void doSomethingDangerous() throws DataAccessException{

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

}
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

Author

Commented:
What's dataaccessexceptiob?I never heard? Is it custom exception?
Top Expert 2015

Commented:
Ok, lets call it Guddi9Exception.

Author

Commented:
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?
Top Expert 2015

Commented:
Yes. The caller may decide the handle it or let it bubble up the call stack and simply do nothing

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial