0

Let's say I have the following code:

public void methodOne(String argumentOne) {
    methodOne(argumentOne, false);
}

public void methodOne(String argumentOne, boolean equality) {
    //App logic here
}

And if the app logic throws an exception (say IllegalArgumentException/Parse Exception), and i would like to catch this in the caller method, should the "throws IllegalArgumentException" be added in all the method identifier or only on the base method identifier? Is there any advantage over this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mohan Krishnan
  • 353
  • 3
  • 16
  • 9
    `IllegalArgumentException` is a `RuntimeException` therefore, it doesn't need to be declared as thrown. – Maurice Perry Dec 10 '18 at 07:47
  • Cool, what about the unchecked Exceptions, like ParseException or Evaluation Exception P.S: Let me change the description in the question too. – Mohan Krishnan Dec 10 '18 at 07:48
  • 1
    `ParseException` is a checked exception. You can either declare it as thrown, or catch it in the method block. – Maurice Perry Dec 10 '18 at 07:50
  • 3
    You should *document* throwing behavior in the JavaDocs of your public interface methods. Behavior in exceptional circumstances is part of the *contract* of your methods, just like which values are valid as input. – Hulk Dec 10 '18 at 07:53
  • 1
    @MohanKrishnan RuntimeExceptions are unchecked exceptions.... – Antoniossss Dec 10 '18 at 07:55

1 Answers1

4

Throwing a checked exception means you expect the caller to be forced to think about how to handle that exception. You should only do this when:

  • This is a deliberate, desirable action in your mind.
  • You have some idea how you expect the caller to deal with a checked exception. Ideally, you have documented what you expect them to do with the exception.

Thus it's a very bad idea to

  • declare "throws" an exception which is never actually thrown. This just causes confusion and get the developer into the habit of ignoring your exceptions as they have no value.
  • throw a checked exception when it is unlikely to be a reasonable way to recover from it. An unchecked exception might be better in that case.

I prefer to add throws clauses for unchecked exceptions as a form of documenting what can go wrong and what it means without forcing the caller to handle those exceptions.

Additionally, you should try to add meaningful messages to each Exception/Error to make it easier for a developer to work out how to fix the code or configuration.

i would like to catch this in the caller method, should the "throws IllegalArgumentException" be added in all the method identifier or only on the base method identifier?

Only add it to the methods which can actually throw the exception.

František Hartman
  • 14,436
  • 2
  • 40
  • 60
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130