A Runtime Exception is an exception that occurs while a program is running and is not checked by the Java compiler during compilation. These exceptions are usually caused by programming mistakes such as accessing an invalid array index, using a null object, or performing an invalid type conversion.
- It can be handled using try-catch blocks to prevent program termination.
- They are unchecked exceptions, so the compiler does not force handling them.
- Usually occur due to logical or programming errors.
// Create public class
public class GFG {
public void GreeksForGreeks()
{
// throw exception
throw new Greeks();
}
public static void main(String[] args)
{
try {
new GFG().GreeksForGreeks();
}
// catch exception
catch (Exception x) {
System.out.println(
"example of runtime exception");
}
}
}
// create subclass and extend RuntimeException class
class Greeks extends RuntimeException {
// create constructor of this class
public Greeks()
{
super();
}
}
Output
example of runtime exception
Explanation: In this example, the Greeks class extends RuntimeException, creating a custom unchecked exception. The GreeksForGreeks() method throws this exception using the throw keyword. The exception is caught in the try-catch block inside the main() method, and the message "example of runtime exception" is displayed instead of terminating the program.
Syntax
try {
// Code that may throw an exception
}
catch (ExceptionType e) {
// Handle the specific exception
}
Common Runtime Exceptions
| Exception | Description |
|---|---|
| NullPointerException | Occurs when a method or field is accessed using a null object reference. |
| ArrayIndexOutOfBoundsException | Occurs when accessing an array using an invalid index. |
| ClassCastException | Occurs when an object is cast to an incompatible type. |
| ArithmeticException | Occurs during illegal arithmetic operations such as division by zero. |
| NumberFormatException | Occurs when converting an invalid string into a numeric type. |
| IllegalArgumentException | Occurs when an invalid argument is passed to a method. |
| IllegalStateException | Occurs when a method is invoked at an inappropriate time or state. |
| UnsupportedOperationException | Occurs when a requested operation is not supported. |
class GFG {
public static void main(String[] args)
{
// create array of 5 size
int[] a = new int[] { 1, 2, 3, 4, 5 };
// execute for loop
for (int i = 0; i < 6; i++) {
// print the value of array
System.out.println(a[i]);
}
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at GFG.main(File.java:10)
Explanation: In this example, an array contains 5 elements (index 0 to 4), but the loop tries to access index 5, which does not exist. This causes Java to throw an ArrayIndexOutOfBoundsException at runtime. Since the exception is not handled using a try-catch block, the program terminates and displays the exception details.