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 zero
int 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, m and n And initialize them.
  • Line 7: We perform the divide by zero operation by dividing m with n and store the result in the variable, r.
  • Line 8: We use System.out.println to print the value stored in r.

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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources