DEV Community

Cover image for Exception Handling for Beginners: try, catch, finally in Java
Sharique Siddiqui
Sharique Siddiqui

Posted on • Edited on

Exception Handling for Beginners: try, catch, finally in Java

No matter how careful you are, errors and unexpected situations can pop up while your Java program runs. Maybe a user enters text when you expect a number, or your code tries to open a file that doesn’t exist. Java’s exception handling features help you manage these events gracefully—so your program doesn’t just crash, but explains what went wrong, or tries to recover.

What Is an Exception?

An exception is a special event that interrupts the normal flow of your program. Common sources of exceptions in Java include:

  • Dividing by zero
  • Accessing an array out of bounds
  • Working with files that don’t exist
  • Invalid user input

If you don’t handle exceptions, your program will stop running and display a confusing error message to the user.

The Exception Handling Structure: try, catch, finally
Java provides a structured way to handle exceptions using three main keywords: try, catch, and finally.

1. The try Block

Place the code that might cause an exception inside a try block. If an exception occurs, the rest of the code in this block is skipped.

java
try {
    // risky code goes here
}
Enter fullscreen mode Exit fullscreen mode

2. The catch Block

If an exception occurs inside the try, Java looks for a matching catch block to handle it. Each catch block handles a specific type of exception.

java
try {
    int result = 10 / 0; // This will cause an exception!
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
}
Enter fullscreen mode Exit fullscreen mode

Output:

text
Cannot divide by zero.
Enter fullscreen mode Exit fullscreen mode

3. The finally Block

The finally block always runs, no matter what. It’s great for cleanup actions—such as closing files or releasing resources.

java
try {
    int[] nums = {1, 2, 3};
    System.out.println(nums[5]); // Out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index is out of range!");
} finally {
    System.out.println("This always runs.");
}

Enter fullscreen mode Exit fullscreen mode

Output:

text
Index is out of range!
This always runs.
Enter fullscreen mode Exit fullscreen mode

Putting It All Together: A Simple Example
Here’s a full example that shows all three blocks in action:

java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("Enter a number: ");
            int num = scanner.nextInt();
            System.out.println("100 divided by " + num + " is " + (100 / num));
        } catch (ArithmeticException e) {
            System.out.println("You cannot divide by zero!");
        } catch (Exception e) {
            System.out.println("Please enter a valid integer.");
        } finally {
            System.out.println("Program finished.");
            scanner.close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Possible Output:

java
Enter a number: 0
You cannot divide by zero!
Program finished.

Enter a number: abc
Please enter a valid integer.
Program finished.

Enter a number: 25
100 divided by 25 is 4
Program finished.
Enter fullscreen mode Exit fullscreen mode

Quick Tips for Beginners

  • Place risky code inside try.
  • Use multiple catch blocks for different types of exceptions.
  • Always include a finally if you have cleanup work, such as closing files or network connections.
  • Not all errors can be caught; for example, "OutOfMemoryError" is not handled the same way as exceptions.

Why Use Exception Handling?

  • Makes your program robust—it won’t just crash on errors.
  • Lets you display user-friendly error messages.
  • Helps prevent resource leaks (e.g., always closing files).
  • Makes debugging and maintenance easier.

Final Thoughts

Learning exception handling is a crucial step toward building reliable Java applications. Practice using try, catch, and finally in small projects—soon, handling errors will feel as natural as writing loops or variables!

Check out the YouTube Playlist for great java developer content for basic to advanced topics.

Please Do Subscribe Our YouTube Channel for clearing programming concept and much more ... : CodenCloud

Top comments (0)