Java try-catch-finally

18-Sep-2024

Learn how to use try-catch-finally blocks in Java to manage errors and resources


In Java, try-catch-finally is used to handle exception that might occurs during the execution of errors.


Syntax:




try {
// put here the code that might throw an exception
} catch (ExceptionType exception) {
// if exception occurs then this block work and exception handle here
} finally {
// this block always execute
}


try: The try block should contain the code from which the exception can be raised.


catch: If an error is caught in the try block then the catch block will execute. And we can handle it according our needs


finally: This block of code will execute always. whether exception is raised or not.




Example:



try {
// put here the code that might throw an exception
int data = 50 / 0; // This will throw ArithmeticException
} catch (ArithmeticException exception) {
// if exception occurs then this block work and exception handle here
System.out.println("ArithmeticException caught: " + exception.getMessage());
} finally {
// this block always execute
System.out.println("This block will always execute.");
}


In this example, we write a line of code for deliberate exception. This line of code will throw an exception of ArithmeticException. The catch block will caught the exception and handle it. and the last finally block will execute.



Comments