- In Java, Runtime Exceptions are errors that occur during the execution of a program. These are also called unchecked exceptions, meaning the compiler does not force you to handle them.
- They usually happen due to programming mistakes.
- In this blog, we will look at some of the most common runtime exceptions and also learn how to handle them properly:
- ArrayIndexOutOfBoundsException
- NullPointerException
- NegativeArraySizeException
- ArithmeticException
What is a Runtime Exception?
A Runtime Exception is an exception that occurs while the program is running.
- These exceptions belong to the RuntimeException class. RuntimeException is a one of the subclass of Exception class.
- Handling is optional, but avoiding them is the best practice
1. ArrayIndexOutOfBoundsException
Definition:
Occurs when accessing an invalid array index.
Example:
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
How to Handle:
try {
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index!");
}
Best Practice: Always check array length before accessing
2. NullPointerException
Definition:
Occurs when using a null object reference.
Example:
String str = null;
System.out.println(str.length());
How to Handle:
try {
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Object is null!");
}
Best Practice: Check for null before using object
if (str != null) {
System.out.println(str.length());
}
3. NegativeArraySizeException
Definition:
Occurs when creating an array with negative size.
Example:
int[] arr = new int[-5];
How to Handle:
try {
int size = -5;
int[] arr = new int[size];
} catch (NegativeArraySizeException e) {
System.out.println("Array size cannot be negative!");
}
Best Practice: Validate input before creating array
4. ArithmeticException
Definition:
Occurs during invalid arithmetic operations.
Example:
int result = 10 / 0;
How to Handle:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
Best Practice: Always check divisor before division
if (b != 0) {
int result = a / b;
}
General Ways to Handle Runtime Exceptions
1. Using try-catch
try {
// risky code
} catch (Exception e) {
System.out.println(e.getMessage());
}
2. Using multiple catch blocks
try {
int[] arr = new int[2];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index issue");
} catch (Exception e) {
System.out.println("General error");
}
3. Using finally block
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println("Error occurred");
} finally {
System.out.println("Always executes");
}
Conclusion
Runtime exceptions occur during execution
They are unchecked exceptions
You can handle them using try-catch
But best practice is to prevent them with proper coding.
Top comments (0)