Exception handling in Java is a powerful mechanism that handles runtime errors to maintain normal application flow. An exception is an event that disrupts the normal flow of the program’s instructions. Java uses a try-catch block to catch exceptions and perform actions to either recover from the error or at least gracefully terminate the program, preventing it from crashing. Below are various examples demonstrating how to handle exceptions in Java.
Basic Try-Catch Block
The simplest form of exception handling is using a try-catch block where you place the code that might throw an exception within a try
block and handle the exception within a catch
block.
Example 1: Handling ArithmeticException
1 2 3 4 5 6 7 8 9 10 |
public class BasicTryCatchExample { public static void main(String[] args) { try { int result = 10 / 0; // This will cause ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); } } } // Output: Cannot divide by zero. |
Multiple Catch Blocks
You can have multiple catch blocks to handle different types of exceptions separately.
Example 2: Handling Multiple Exceptions
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class MultipleCatchExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // This will cause ArrayIndexOutOfBoundsException } catch (ArithmeticException e) { System.out.println("Arithmetic Exception occurred."); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array Index Out Of Bounds Exception occurred."); } } } // Output: Array Index Out Of Bounds Exception occurred. |
Finally Block
The finally
block executes after the try-catch blocks regardless of whether an exception was thrown or caught. It’s typically used for cleanup activities.
Example 3: Using Finally Block
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class FinallyExample { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Caught an arithmetic exception."); } finally { System.out.println("This is always executed."); } } } // Output: // Caught an arithmetic exception. // This is always executed. |
Try-With-Resources
Java 7 introduced the try-with-resources statement, which automatically closes resources (files, streams) used within the try block.
Example 4: Try-With-Resources
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TryWithResourcesExample { public static void main(String[] args) { String line; try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) { while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("IOException occurred."); } } } // Output depends on the contents of test.txt |
Custom Exceptions
You can also create your own custom exception classes by extending the Exception
class.
Example 5: Custom Exception
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class CustomExceptionExample { static class MyCustomException extends Exception { public MyCustomException(String message) { super(message); } } public static void checkNumber(int number) throws MyCustomException { if (number < 10) { throw new MyCustomException("Number is less than 10"); } } public static void main(String[] args) { try { checkNumber(5); } catch (MyCustomException e) { System.out.println(e.getMessage()); } } } // Output: Number is less than 10 |
Conclusion
Exception handling in Java is crucial for building robust applications. By effectively using try-catch blocks, finally blocks, try-with-resources statements, and creating custom exceptions, developers can ensure that their programs handle errors gracefully, providing a better user experience and preventing crashes during runtime.