Search code examples
javaexceptionerror-handlingtry-catchruntimeexception

Java: Using Catch and throws in the one block?


What is the point of catching and then also throwing an Exception like below? Is it bad practice to do both?

  try{

    //something

    } catch (Exception e){

    throw new RuntimeException("reason for exception");
    }

Solution

  • Usually, such code is used to re-wrap exceptions, that means transforming the type of the exception. Typically, you do this when you are limited in what exceptions are allowed out of your method, but internally other types of exceptions can happen. For example:

    class MyServiceImplementaiton implements MyService {
        void myService() throws MyServiceException { // cannot change the throws clause here
            try {
                .... // Do something
            } catch(IOException e) {
                // re-wrap the received IOException as MyServiceException
                throw new MyServiceException(e); 
            }
        }
    }
    

    This idiom enables to keep propagating exceptions to the caller, while conforming to the throws clause in the interface and hide the details of the internals (the fact that IOExceptions can happen).

    In practice, this is always better than just calling e.printStackTrace() which will actually "swallow" the error condition and let the rest of the program run as if nothing had happened. In this respect, behaviour of Eclipse is quite bad as it tends to auto-write such bad-practice constructs if the developer is not careful.