Exception Handling Keywords in Java
What is an Exception? An exception is an unwanted event that occurs during program execution. Example: Dividing a number by zero Accessing null object File not found 1. try Block The try block cont...

Source: DEV Community
What is an Exception? An exception is an unwanted event that occurs during program execution. Example: Dividing a number by zero Accessing null object File not found 1. try Block The try block contains code that may cause an exception. Syntax: try { // risky code } Example: try { int a = 10 / 0; // exception } Where we use: --> Database operations --> File handling --> Network calls 2. catch Block The catch block handles the exception thrown in the try. Syntax: catch(Exception e) { // handling code } Example: try { int a = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } Where we use: --> To show user-friendly messages --> To prevent program crash 3. finally Block The finally block always executes whether an exception occurs or not. Syntax: finally { // cleanup code } Example: try { int a = 10 / 2; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("Always executed"); } Real-time use: --> Closing