Article:
  Best Practices for Exception Handling
Subject:   throw new Exception("...")
Date:   2003-11-19 22:48:53
From:   anonymous2
Very good article, but there is one contradiction. The article says in '3. Try not to create...':


'But if you are not going to add extra information, then just throw a standard exception:
throw new Exception("Username already taken")'


This forces the client code to cast the net wide by catching 'Exception'. The article later states that this should be avoided:


'4. Do not catch top-level exceptions'

Full Threads Newest First

Showing messages 1 through 2 of 2.

  • throw new Exception("...")
    2003-11-20 01:59:31  anonymous2 [View]

    I agree. Also sometimes just subclassing the exception class makes it easier, in client code, to determine what exactly went wrong.

    Catching an empty DuplicateUserName exception means I have a far better idea of what went wrong than by catching an Exception and then having to query the message to find out what its about. So if you are going to do some specific recovery stuff for specific exception types then I can't see a problem with subclassing Exception and adding no new methods.
  • throw new Exception("...")
    2003-11-20 09:46:28  gunjandoshi1 [View]

    When I wrote this article, I was arguing with myself to put the line. I wrote this line with two motives:

    1.)I wanted to make a smooth transition to the next line that is:

    "Even better, if you think the client code is not going to take any action other than logging if the username is already taken, throw a unchecked exception:
    throw new RuntimeException("Username already taken");"

    It is difficult for some programmers to think about converting CheckedExceptions to RuntimeExceptions.

    2.) I wanted to show that you could achieve the same affect as creating a new Exception class with throwing a plain Exception. However, I do NOT advise people to throw plain Exception classes. My recommendation is to convert the exception into a RuntimeException if the client cannot do anything against it.