-1

In Java why do we have two types of exceptions checked and unchecked. while checked exceptions force us to wrap the methods in try..catch. What if those are not checked and we throw the errors anyway

ketaki
  • 25
  • 5

1 Answers1

0

The original intention was that checked exceptions related to situations that a developer was expected to be able to handle, whilst unchecked exceptions would be for situations that a developer probably could not handle (out of memory, internal JVM errors). Making an exception checked has the effect that the developer must take account of it -- it can't just be overlooked because the code won't compile.

If an unchecked exception is not handled -- not anywhere -- then it will shut down the JVM. In practice, most application-hosting frameworks (webservers, application containers) will catch unchecked exceptions if the application does not, rather than letting the JVM shut down. It would be unfortunate if, for example, an unchecked exception thrown from code in a servlet caused the whole webserver to shut down.

The original division of exceptions from the JVM basic classes into "checked" and "unchecked" categories is, to my mind, a little arbitrary. For example, I've never really understood why the basic string-to-number conversion functions throw the unchecked NumberFormatException, when a developer really ought to be handling incorrectly-formatted data. Still, that's just the way it is.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15
  • 1
    Sorry, but there is a lot wrong in this answer. In your first paragraph, you're confusing Exceptions and Errors (at least OutOfMemory is an Error) which is a different topic. In your second paragraph you state that any non-catched Exception (and Error) will lead to the shutdown of the JVM. That's not true, it just leads to the end of the Thread where the exception occurred, so a complete webserver shouldn't shutdown because of this (of course if all processing threads get lost over time due to this effect, you end up with a non-functioning webserver but still you have to restart it yourself) – Lothar Sep 01 '17 at 09:45
  • I read the question as asking why there are these different kinds of exception in Java, rather than what the fine technical distinction is. The technical distinction is documented in the platform spec, etc. OutOfMessageError is "unchecked" to the extent that you can throw it from a method without declaring it to be thrown. Your point about threads is correct, but it wouldn't normally be considered good practice in an application hosting environment to allow an unchecked exception (or any kind of Throwable) to propagate up to the JVM without being handled. – Kevin Boone Sep 02 '17 at 10:24