Try-Catch Blocks
Exception handling in Java is done using the try
, catch
, and finally
blocks. This tutorial will teach you how to handle exceptions in your code.
Using Try-Catch
The try
block contains code that might throw an exception, while the catch
block contains code that handles the exception:
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");
}
}
}
In this example, the try
block contains code that throws an ArrayIndexOutOfBoundsException
, which is then caught and handled in the catch
block.
Multiple Catch Blocks
You can have multiple catch
blocks to handle different types of exceptions:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Division by zero!");
} catch (Exception e) {
System.out.println("Exception: Something went wrong.");
}
}
}
Finally Block
The finally
block contains code that is always executed, whether an exception is thrown or not:
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");
} finally {
System.out.println("This block is always executed.");
}
}
}
Continue exploring our intermediate tutorials to learn more about Java programming.