What are unchecked exceptions in Java?
Overview
In Java, an unchecked exception is an unexpected error that occurs at runtime and leads to the termination of the program execution. These exceptions are also called runtime exceptions and are ignored during code compilation. Examples of unchecked exceptions include ArithmeticException, ArrayIndexOutOfBoundsException and so on.
Example
Let's see an example of an ArithmeticException:
class Example {public static void main( String args[] ) {int m = 10;int n = 0;// performing divide by zeroint r = m/n;System.out.println(r);}}
Explanation
- Line 1: We create a class,
Example. - Line 2: We define the
main()function. - Lines 3–4: We declare two variables,
mandnAnd initialize them.
- Line 7: We perform the
divide by zerooperation by dividingmwithnand store the result in the variable,r. - Line 8: We use
System.out.printlnto print the value stored inr.
Output
At the time of compilation, the divide by zero will not be caught since there's no syntactical mistake. However, we know it is arithmetically incorrect because division by zero is not possible. Therefore, the compiler allows the code to compile. However, during the execution, this error is caught, and it throws an ArithmeticException, which leads to the termination of our program execution.