Related Topics

JAVA Programming
String str = null;
int length = str.length(); // This line will throw a NullPointerException
In this example, the str
variable is assigned a null value, and the subsequent line tries to access the length()
method on it. Since the variable is null, the program will throw a NullPointerException
.
The purpose of the NullPointerException
is to help developers identify and fix issues with null references in their code. By throwing this exception, the program is indicating that there is a problem that needs to be addressed.
int dividend = 5;
int divisor = 0;
try {
int result = dividend / divisor;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
In the above example, an ArithmeticException
will be thrown because we are trying to divide dividend
by zero. The catch block will then catch the exception and print the message “Cannot divide by zero.”
int[] arr = new int[3];
arr[3] = 4;
In this code, an ArrayIndexOutOfBoundsException
will be thrown because the index 3
is outside the bounds of the arr
array, which has a length of 3
.
This exception can also be thrown by other methods that take an index as a parameter, such as String.charAt(int index)
or List.get(int index)
, when an invalid index is provided.
In general, this exception is thrown when there is an attempt to access an array or collection with an index that is out of bounds. It is a common runtime exception that can be caught and handled like any other exception.




Popular Category
Topics for You
Go through our study material. Your Job is awaiting.