Exception handling is how you keep the whole program from crashing when an error happens at runtime. You put code that might error inside a try block, and if an error occurs, catch handles it. finally runs whether or not an error happened.
java
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index. Please choose an item inside the array.");
} finally {
System.out.println("Array check finished.");
}
}
}The array only has indexes 0, 1, and 2, but calling numbers[5] triggers an exception. The catch block catches the error and prints a user-friendly message.
You should see
Invalid index. Please choose an item inside the array. Array check finished.Real-World Use
Without exception handling, things like file reading, API calls, database queries, payment requests, and parsing user input can easily crash a production app.