0

Should one re-throw a runtime exception as a checked exception, where a client could sensibly anticipate and handle the situation.

It seems to me that is the purpose of checked exceptions, and surely since such anticipatable and handleable scenarios can occur in runtime exceptions as well as checked exeptions - would it not make sense to treat them the same.

Should one do this through listing runtime exceptions in the throws clause - and hope? Does rethrowing it as a user defined checked exception help in this respect (by forcing through the compiler a client to handle it)?

Edit:

(for instance where one might encounter a NumberFormatException when reading files that may be supplied)

1 Answers1

1

RuntimeExceptions are basically logical errors. And logical errors should be corrected in code instead of throwing them across your code base.

Exceptions are scenarios which occur rarely but when do, the flow of program changes drastically.

You CAN wrap a RuntimeException into a checked exception but That's NOT recommended. A logical error in your method is not supposed to be handled outside your method and more bad if you providing your method to be used as an API to other developers.

To add one more point, If you are developing a framework it seems logical to throw the RuntimeException so that developers can handle it by correcting their code but if you are developing a library, be far far away from doing that.

To know difference between framework and library see this: What is the difference between a framework and a library?

Community
  • 1
  • 1
Azodious
  • 13,385
  • 1
  • 32
  • 68
  • Many thanks for your answer, I appreciate the comprehensiveness of your post. The confusion I have though, is in the cases where the RuntimeException is thrown for a reason _that is not a logical error_ - the position im coming from is - I thought the whole purpose of exceptions is to practise exception handling (to design your program such that upon encountering a rare exceptional situation, it may recover as best as possible (save work/ progress, or roll the system back to a safe or valid state) or at least allow the program to clean up before – keen_coder Dec 13 '16 at 13:40
  • closing or rolling back to a safe state (closing resources etc) - rather than just terminating badly with an error message. I suppose my question is, how should one deal with RuntimeExceptions that are not program logic error (and cannot be fixed or avoided by correcting any code - where there is no code that needs correcting). – keen_coder Dec 13 '16 at 13:40
  • @keen_coder Give your description of the situation, I would indeed wrap the unchecked exception in a checked exception. – VGR Dec 13 '16 at 15:34