Java
Beginner
1 min read
try-catch-finally Blocks
Example
public class TryCatchDemo {
static int divide(int a, int b) {
try {
System.out.println("Attempting division...");
return a / b;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
return -1;
} finally {
// Always runs, even if exception not thrown
System.out.println("finally block executed");
}
}
static void multiCatch(String[] args, int index) {
try {
String value = args[index];
int num = Integer.parseInt(value);
System.out.println("Parsed: " + num);
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
// Multi-catch: single handler for two types
System.out.println("Multi-catch: " + e.getClass().getSimpleName()
+ " - " + e.getMessage());
}
}
static void exceptionChaining() {
try {
try {
throw new java.io.IOException("disk full");
} catch (java.io.IOException e) {
// Wrap and rethrow with context
throw new RuntimeException("Failed to save data", e);
}
} catch (RuntimeException e) {
System.out.println("Top-level: " + e.getMessage());
System.out.println("Caused by: " + e.getCause().getMessage());
}
}
public static void main(String[] args) {
System.out.println("Result: " + divide(10, 2));
System.out.println("Result: " + divide(10, 0));
multiCatch(new String[]{"42"}, 0);
multiCatch(new String[]{"abc"}, 0);
multiCatch(new String[]{}, 5);
exceptionChaining();
}
}