Divya Somashekar
Divya Somashekar

Reputation: 51

Is it good coding practice to throw in catch block?

I'm doing some service related operation. is the below snippet valid?

try {
          //some code here
    } catch (ServiceException e) {
                throw new ServiceException("Error!!!");
   }

I'm catching ServiceException and throwing the same exception. Is it good practice ???

Upvotes: 1

Views: 3791

Answers (3)

Ioan M
Ioan M

Reputation: 1207

You are not sure whether what you've written is good or bad. In this situation I would document myself a bit about the tools I plan to use, in this case the Exception mechanism from Java and then I would start asking questions:

  1. Is there a reason why I should catch ServiceException e and then throw another one of the same type with less info in it. You created the new one with less information. String "Error!!!" is definitely less than what you can probably get from the original e.getMessage() or e.getCause etc (assuming ServiceException e is maybe wrapping another low level exception, document yourself a bit about Exception wrapping).
  2. Will some calling code catch a ServiceException and act on it? Check a bit your call hierarchy and find the place where you have to act on ServiceException. Stop there and start asking again. Does it make any difference if here I catch a ServiceException with "Error!!!" in it or the original ServiceException e.
  3. I am throwing and catching Exceptions in my code, do I have to somehow track later what happened here? If yes then I would also log some errors, warnings or infos about what happened, depending on the scenario. This way you will make the troubleshooting process easier for someone who's inspecting later the logs of your application. I would also read a bit about swallowing exceptions and why it is bad to do it.

Upvotes: 0

任志强
任志强

Reputation: 1

not good practice. because it is hard to find origin reason for the problem

Upvotes: 0

SRK
SRK

Reputation: 145

In catch part you actually catch main exception that occurred during code..and then you throw custom/ user readable exception from that..This is good practice.

Upvotes: 2

Related Questions