The try-catch-finally
block is used in Java for exception handling. The try
block contains code that might throw an exception, the catch
block handles the exception, and the finally
block contains code that executes regardless of whether an exception is thrown.
NOTE:
The try-catch-finally order is very important.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
xxxxxxxxxx
import java.io.*;
public class Example1 {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}
Cannot divide by zero.
try {
// Code that might throw an exception
} finally {
// Code that will always execute
}
xxxxxxxxxx
import java.io.*;
public class Example2 {
public static void main(String[] args) {
try {
int result = 10 / 0;
} finally {
System.out.println("This is the finally block.");
}
}
}
This is the finally block.
Exception in thread "main" java.lang.ArithmeticException: / by zero
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
xxxxxxxxxx
public class Example3 {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This is the finally block.");
}
}
}
Cannot divide by zero.
This is the finally block.
try {
// Code that might throw an exception
}
// No catch or finally block
catch (ExceptionType e) { // invalid
// Code to handle the exception
}
finally { // invalid
// Code that will always execute
}
try {
// Outer try block
try {
// Inner try block
} catch (ExceptionType e) {
// Inner catch block
} finally {
// Inner finally block
}
} catch (ExceptionType e) {
// Outer catch block
} finally {
// Outer finally block
}
xxxxxxxxxx
public class Example8 {
public static void main(String[] args) {
try {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch: Cannot divide by zero.");
} finally {
System.out.println("Inner finally block.");
}
} catch (Exception e) {
System.out.println("Outer catch: General exception.");
} finally {
System.out.println("Outer finally block.");
}
}
}
Inner catch: Cannot divide by zero.
Inner finally block.
Outer finally block.