Java: Why You See the "Unhandled exception" Warning

unhandled-exception

Sometimes you would see such warning msg like the above in your Intellij, this means you need to handle the exception: add exception to method signature, or surround with try/catch. But why you can throw some exceptions without these handling, and why you can't throw some?

The key is checked/unchecked exceptions. You must handle checked exceptions, and are not required to handle unchecked exceptions.

Checked Exception

Checked exceptions represent errors outside the control of the program, and Java verifies checked exceptions at compile-time.[1] You must handle them.

Unchecked Exception

Unchecked exceptions are typically unrecoverable runtime failure due to developer's illegal operation or errors in program's logic or by some JVM failures like out of memory situations[2]. Java does not verify unchecked exceptions at compile-time. You don't need to handle them.

The below image shows types of exceptions in these two categories.

checked-unchecked-exception

References


  1. Checked and Unchecked Exceptions in Java ↩︎

  2. Java - checked vs unchecked exceptions ↩︎