Types of exceptions in Java
Types of exceptions
5
In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are typically caused by errors in our code or in the environment in which the code is being executed. To handle these exceptions, Java provides a mechanism called exception handling.
There are two types of exceptions in Java: checked and unchecked exceptions.
- Checked Exceptions
Checked exceptions are checked by the compiler at compile-time. This means that we must handle or declare these exceptions in the code. If we do not handle or declare a checked exception, the program will not compile. Checked exceptions are used for conditions that we can anticipate but canโt handle at runtime. Some examples of checked exceptions are FileNotFoundException, IOException, SQLException.
- Unchecked Exceptions
Unchecked exceptions are not checked by the compiler at compile-time. These exceptions are caused by programming errors such as null pointer exceptions or illegal argument exceptions. Since these errors are caused by programming mistakes, we can catch and handle these exceptions ourselves. Some examples of unchecked exceptions are NullPointerException, IndexOutOfBoundsException, and ArrayIndexOutOfBoundsException.
In summary, Java provides two types of exceptions: checked and unchecked. Checked exceptions must be handled or declared in the code, while unchecked exceptions can be handled within the code. By understanding these different types of exceptions, we can write more robust and error-free Java code.
March 25, 2023