DEV Community

Jane for Mastering Backend

Posted on • Originally published at masteringbackend.com

Exception Handling in java (try, catch & finally)

title

What is an Exception?

An exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runtime) and disrupts the normal flow of the application.

Exception Handling

Java Exception Handling is a way to detect, handle, and recover from unwanted or unexpected events (exceptions) that occur during the execution of a program. It allows the program to deal with runtime errors gracefully, without crashing, by providing alternative flows or meaningful error messages.

image (29).pngExample:

Imagine you’re using a food delivery app. You place an order, but your internet disconnects for a moment. Instead of crashing, the app shows a message:

"No Internet Connection. Please try again."

This is possible because of exception handling. The app catches the error and shows a friendly message instead of terminating .

What is Error?

An Error is something that goes wrong in our program that we usually cannot fix, such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.

Difference Between Exception and Error

Differences

Example

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<int[]> list = new ArrayList<>();

        while (true) {
            // Allocating large chunks of memory repeatedly
            list.add(new int[1000000]);
            System.out.println("Added another array to the list");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

In this example, allocating large chunks of memory repeatedly that why we get an error that is OutOfMemoryError that we cannot fix easily.

Added another array to the list
Added another array to the list
...
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Exception Handling Hierarchy

Throwable is the class that is the super class of all the types of exception, that’s comes at the top of the exception class hierarchy.

image (30).pngChecked Exceptions

  • Checked Exceptions are the exceptions that occurs at compile time.

  • Java force us to handle it.

  • IOException, SQLException

  • Java forces us to handle these using try-catch or throws.

Here are some mostly occurs checked exceptions

checked exceptions

Unchecked Exceptions

  • Checked Exceptions are the exceptions that occurs at run time.

  • Java does NOT force us to handle it.

  • NullPointerException, ArithmeticException

Here are some mostly occurs unchecked exceptions

unchecked exceptions

Key Components of Java Exception Handling

  • try

  • catch

  • finally

  • throw

  • throws

try

  • he try block is used to enclose risky code, code that may potentially throw an exception during program execution.

  • When an exception occurs inside the try block, Java throws an exception object that contains information about the error, including its type and a stack trace.

  • A try block must be followed by either a catch block, a finally block, or both.

  • A single try block can be followed by multiple catch blocks to handle different types of exceptions.

catch

  • The catch block, also known as the handler block, is used to handle exceptions thrown by the try block.

  • It catches the exception object and provides a way to respond to the error, such as displaying a message or taking corrective action.

  • A catch block cannot exist on its own, it must always follow a try block.

finally

  • The finally block can be used after a try block, with or without a catch block.

  • It contains code that is always executed, whether an exception occurs or not.

  • You can use the finally block alongside a catch block, or directly after a try block if no catch is needed.

  • A single try block can have only one associated finally block.

try-catch

image (31).png

try with Multiple catch Blocks

Multiple catch blocks can be associated with a single try block to handle different exception types.

image (32).png try-catch-finally

image (33).png try-finally

A finally block can be used directly after a try block, even without a catch block.

image (34).pngHow Does Java Handle Exceptions?

Java has a smart way to handle errors. When something goes wrong during the program’s execution, Java creates an exception object. This object holds details about the error, like:

  • What kind of error occurred

  • Where it occur in the program

This error (exception) is then thrown, and Java looks for a place in your code where the error can be caught and handled.

Java uses two main blocks for this:

  • try block: This is where you write code that might cause an error.

  • catch block: This catches the error and tells the program what to do next, so it doesn’t crash.

image (35).pngJava uses exception handling to deal with errors that happen when a program is running. This helps the program avoid crashing and instead handle the problem smoothly.

When the program starts, it runs the code inside a try block. If everything works fine, the code runs normally. But if an error happens (like dividing a number by zero), Java stops the try block and moves to the catch block.

For example, the line int result = 10 / 0; causes an error because you can’t divide by zero. Java catches this error and shows a friendly message like: “An error occurred: / by zero.” Then the program continues and ends normally.

This is very helpful in real apps. For example, if a food delivery app loses internet, it doesn’t crash. Instead, it shows a message like “No internet, please try again.” That’s exception handling in action!

Example:

public class MasteringBackend {
    public static void main(String[] args) {
        System.out.println("Start"); // Flowchart: Start

        try {
            // Step 1: Run code that might throw an exception
            int result = 10 / 0; // This will throw ArithmeticException
            System.out.println("Successful"); // Flowchart: Successful
        } catch (ArithmeticException e) {
            // Handle the exception
            System.out.println("An error occurred: " + e.getMessage());
        }

        // End of program
        System.out.println("End");
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output

Start
An error occurred: / by zero
End
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Notes

  • We cannot write two catch blocks that handle the same exception type.

  • When using multiple catch blocks:

    • If the exceptions do not have an "is-a" relationship, the order doesn't matter.
    • If they do, the child class must come before the parent class.
  • try, catch, and finally blocks can be nested.

  • A single try block can have multiple catch blocks and one finally block.

Have a great one!!!

Author: Solomon Eseme


Thank you for being a part of the community

Before you go:

Whenever you’re ready

There are 4 ways we can help you become a great backend engineer:

  • The MB Platform: Join thousands of backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.
  • The MB Academy: The “MB Academy” is a 6-month intensive Advanced Backend Engineering Boot Camp to produce great backend engineers.
  • Join Backend Weekly: If you like posts like this, you will absolutely enjoy our exclusive weekly newsletter, sharing exclusive backend engineering resources to help you become a great Backend Engineer.
  • Get Backend Jobs: Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board.

Top comments (0)