Exception handling is an essential part of Java programming, ensuring that applications run smoothly by catching and managing runtime errors. Java provides the try
, catch
, and finally
blocks to handle exceptions effectively.
try Block
The try
block is where we place the code that might throw an exception. If an exception occurs, it is passed to the corresponding catch
block for handling.
Syntax
1 2 3 |
try { // Code that might throw an exception } |
Example
1 2 3 4 |
try { int result = 10 / 0; // This will throw an ArithmeticException System.out.println(result); } |
catch Block
The catch
block follows the try
block and handles specific exceptions. If an exception occurs inside the try
block, the catch
block executes.
Syntax
1 2 3 4 5 |
try { // Code that may throw an exception } catch (ExceptionType e) { // Handling code } |
Example
1 2 3 4 5 6 |
try { int arr[] = {1, 2, 3}; System.out.println(arr[5]); // ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index is out of bounds!"); } |
finally Block
The finally
block contains code that will execute whether an exception occurs or not. It is mainly used for cleanup operations, such as closing database connections or file streams.
Syntax
1 2 3 4 5 6 7 |
try { // Code that might throw an exception } catch (ExceptionType e) { // Handling code } finally { // Cleanup code } |
Example
1 2 3 4 5 6 7 8 9 10 11 |
try { int num = Integer.parseInt("Java"); // NumberFormatException } catch (NumberFormatException e) { System.out.println("Invalid number format!"); } finally { System.out.println("Execution completed."); } //Output Invalid number format! Execution completed. |