Java RuntimeException
Example
Catch an array error as a RuntimeException:
public class Main {
public static void main(String[] args) {
int[] myNumbers = {1, 2, 3};
try {
System.out.println(myNumbers[10]);
} catch (RuntimeException e) {
System.out.println("Something went wrong.");
}
}
}
Definition and Usage
RuntimeException is the parent class of the exceptions that can happen while a program runs, often because of a mistake in the code. NullPointerException, ArithmeticException and ArrayIndexOutOfBoundsException are all kinds of RuntimeException.
They are unchecked exceptions: Java does not require you to catch them, or to declare them with throws. A catch (RuntimeException e) block catches all of them.
Tip: You can also throw it yourself: throw new RuntimeException("Something went wrong");
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions