An exception is an object that contains information about the error. We should anticipate and handle these exceptions properly. Every kind of exception has an error message and a stack trace.
Checked exceptions are the exceptions that a developer should anticipate and handle, In other words, the we should check for their existence. Hence the name checked exception.
For example while reading a file, If the file is not found then a FileNotFoundException
might be thrown. This is a type of checked exception which should be handled. Compiler enforces these type of exceptions to be handled and hence they are known as checked exceptions. As they get checked at compile time.
Unchecked exceptions are the exceptions which do not get checked at compile time but rather at runtime. These type of exception mostly occur due to programming errors. These exception are unpredictable at the compile time and hence cannot be checked at compile time.
Common runtime exceptions are — NullPointerException | ArithemeticException | illegalArgumentException | IndexOutOfBoundException | IllegalStateException
.
Exception uses the hierarchical design pattern to share common behaviors between different exceptions. At the top level we have the Throwable
class. It has 2 children — Error
& Exception
Error
class → any kind of error external to our application belongs to this class.Exception
class → any exception that belongs to this class is a checked exception. The Exception
class has another child — RuntimeException
class.
RuntimeException
class → All unchecked exception belongs to this class.<aside> ⚠️
A common confusion might occur, that the unchecked exceptions are also a type of checked exception but they are not.
</aside>
https://lh7-us.googleusercontent.com/w9Na1fbAmrwSfyUdTn4o4xWoEITqae7HcrHZiJE0r7pg9cGNzCNH9w9AAT4UoSZ8wnh9416Sz01E4-hNLfrrdfwqxK0c0K2AiQsXT9JoIlB43HUOLqqDRzP5rTjXm2jmfMO8bEahG_RNrSn_m-HwKZo