Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
exceptions
communitycreator

What are unchecked exceptions in Java?

Shubham Singh Kshatriya

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);
    }
}
Example of ArithmeticException in Java

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.

RELATED TAGS

java
exceptions
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring