Welcome to our comprehensive guide on the Java Try-Catch Block! This tutorial is designed for beginners and intermediates, providing an in-depth understanding of this essential Java feature. š
Exception handling is a mechanism that allows a program to continue running even when an error occurs. In Java, we use the Try-Catch block for this purpose.
try {
// code that might throw an exception
} catch (ExceptionType1 e1) {
// code to handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// code to handle exception of type ExceptionType2
}š” Pro Tip: The try block contains the code that may throw an exception. The catch blocks are used to handle these exceptions.
ExceptionThis is the root class for all exceptions in Java. It is seldom used directly.
RuntimeExceptionSubclasses of RuntimeException are unchecked exceptions, which do not need to be declared in method signatures. Common examples include NullPointerException, ArrayIndexOutOfBoundsException, and IllegalArgumentException.
ErrorErrors are exceptions that occur at runtime, but they are usually not caused by programming errors. Examples include OutOfMemoryError and StackOverflowError.
Let's write a simple example to demonstrate the Try-Catch block.
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[4]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds!");
}
}
}In this example, we're trying to access an array element at index 4, which does not exist. The ArrayIndexOutOfBoundsException is caught and handled by the catch block.
What will be the output of the following code?