Java Exceptions (Practical)

How to Handle Exceptions

1. Using try-catch block

The try-catch block is the most common way to handle exceptions. The code that might throw an exception is placed inside the try block, and the code to handle the exception is placed inside the catch block.

public class example1 {
public static void main(String[] args) {
try {
// Code that might throw an exception
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
// Code to handle the exception
System.out.println("Cannot divide by zero.");
}
}
}

Step-by-Step Explanation:

  • Try block: This block contains the code that might throw an exception.
  • Catch block: If an exception occurs in the try block, the catch block is executed. The exception object is passed as an argument to the catch block.
  • Handling the exception: Inside the catch block, you write code to handle the exception, like logging an error message or providing a default value.

2. Using finally block

The finally block is used to execute code after the try and catch blocks, regardless of whether an exception was thrown or not. It is commonly used for cleanup activities, like closing a file or releasing resources.

public class example1 {
public static void main(String[] args) {
try {
// Code that might throw an exception
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
// Code to handle the exception
System.out.println("Cannot divide by zero.");
} finally {
// Code that will always run
System.out.println("This will always be executed.");
}
}
}

Step-by-Step Explanation:

  • Finally block: This block is optional but highly recommended for cleaning up resources.
  • It always executes whether an exception is caught or not.
  • Use it to release resources like file handles, database connections, etc.

Comments