Try-Catch-Finally

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 with Catch (Valid)
try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}
Output
Cannot divide by zero.
Try with Finally (Valid)
try {
    // Code that might throw an exception
} finally {
    // Code that will always execute
}
Output
This is the finally block.
Exception in thread "main" java.lang.ArithmeticException: / by zero
Try with Catch and Finally
try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that will always execute
}
Output
Cannot divide by zero.
This is the finally block.
Try without Catch or Finally (Invalid)
try {
    // Code that might throw an exception
}
// No catch or finally block
Catch without Try (Invalid) And Finally without Try (Invalid)
catch (ExceptionType e) { // invalid
    // Code to handle the exception
}
finally { // invalid
    // Code that will always execute
}
Nested Try-Catch-Finally (Valid)
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
}
Output
Inner catch: Cannot divide by zero.
Inner finally block.
Outer finally block.