What Are the Common Runtime Exceptions in Java?

What Are the Common Runtime Exceptions in Java? Learn with Code Examples

Java, as a robust and flexible programming language, provides developers with an extensive mechanism for handling errors through exceptions. Runtime exceptions are one of the most common types of exceptions you will encounter while developing Java applications. These exceptions occur during the execution of a program and are typically a result of bugs or logical errors in the code.

In this article, we will dive deep into the most common runtime exceptions in Java, explain their causes, and illustrate each one with clear and practical code examples. We will also explore how to handle these exceptions to improve your Java application’s stability.


1. NullPointerException

NullPointerException occurs when the JVM attempts to access an object or method through a reference variable that points to null. This is one of the most frequently encountered runtime exceptions in Java.

Example:

public class NullPointerExample {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.length()); // This will throw NullPointerException
    }
}
        

To avoid this exception, ensure that objects are properly initialized before accessing their members.


2. ArithmeticException

ArithmeticException is thrown when an illegal arithmetic operation occurs, such as dividing a number by zero.

Example:

public class ArithmeticExceptionExample {
    public static void main(String[] args) {
        int result = 10 / 0; // This will throw ArithmeticException
        System.out.println(result);
    }
}
        

To handle this exception, you should check for potential division by zero before performing the division.


3. ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException occurs when an array is accessed with an invalid index, either greater than or equal to the array’s length, or a negative index.

Example:

public class ArrayIndexOutOfBoundsExample {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println(arr[5]); // This will throw ArrayIndexOutOfBoundsException
    }
}
        

To avoid this exception, always ensure that the index is within the bounds of the array.


4. ClassCastException

ClassCastException occurs when an attempt is made to cast an object to a subclass of which it is not an instance.

Example:

public class ClassCastExample {
    public static void main(String[] args) {
        Object obj = new Integer(100);
        String str = (String) obj; // This will throw ClassCastException
    }
}
        

To prevent this exception, ensure that the object is cast only to the correct type.


5. IllegalArgumentException

IllegalArgumentException is thrown when a method receives an argument that is inappropriate or illegal. This exception is often used to indicate that the caller of the method has passed an argument that violates the method’s contract.

Example:

public class IllegalArgumentExceptionExample {
    public static void main(String[] args) {
        int age = -5;
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
    }
}
        

This exception can be avoided by validating input values before using them in methods.


6. NumberFormatException

NumberFormatException occurs when an attempt is made to convert a string into a number, but the string does not represent a valid number.

Example:

public class NumberFormatExceptionExample {
    public static void main(String[] args) {
        String str = "abc";
        int number = Integer.parseInt(str); // This will throw NumberFormatException
    }
}
        

To avoid this exception, always ensure that the string can be parsed into a valid number.


Conclusion

Runtime exceptions are a fundamental part of Java's error-handling framework. While these exceptions are not checked by the compiler, they are still essential to understand and handle to ensure that your applications run smoothly.

By using appropriate error handling mechanisms such as try-catch blocks and validating input, you can reduce the occurrence of runtime exceptions and improve the stability of your Java programs.

Please follow and like us:

Leave a Comment