RuntimeException
RuntimeExceptions
do not require try/catch blocks in the code. They can usually be avoided with proper care when coding. However, when mistakes are not detected and the RuntimeException
is uncaught, it will cause the application to fail and display issue information that the user may not always understand. In this exercise, you will see what happens when you don't catch a possible RuntimeException
and what happens when you do try/catch them.
This exercise is part of the course
Data Types and Exceptions in Java
Exercise instructions
- Examine the
withoutTryCatch()
andwithTryCatch
methods in this application and note difference between them. - Run the application without changes - which results in the
withoutTryCatch()
method to execute that causes aRuntimeException
. - Comment out line 5 and uncomment line 7, and then rerun the application - which results in the
withTryCatch()
method executing which this time handles theRuntimeException
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class RuntimeExceptionHandling {
public static void main(String[] args) {
// Comment out this line
withoutTryCatch();
// Uncomment this line
// withTryCatch();
}
public static void withoutTryCatch() {
String[] mounts = { "Everest", "K2", "Kangchenjunga", "Lhotse" };
String selectedMount = mounts[4];
System.out.println("Selected item is: " + selectedMount);
}
public static void withTryCatch() {
try {
String[] mounts = { "Everest", "K2", "Kangchenjunga", "Lhotse" };
String selectedMount = mounts[4];
System.out.println("Selected item is: " + selectedMount);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Oops - made a mistake accessing the mounts array with a bad index.");
}
}
}