LeetCampus
Interview Question

How does an exception propagate in the code?

July 24, 2025
0 views
Difficulty: Medium
Popularity: Common
Share on

Question Explanation

Exception propagation refers to the process by which exceptions are passed up the call stack until they are caught by an appropriate exception handler. Understanding this concept is crucial for developers, as it affects how robust and maintainable their code is. When an exception is thrown, the runtime searches for a corresponding catch block, starting from the point where the exception originated, and moving up the call stack through the method calls. If no handler is found, the program may terminate unexpectedly. This question is commonly asked in interviews to assess a candidate's grasp of error handling and control flow in programming. Interviewers want to ensure that candidates can write resilient code that gracefully handles errors without crashing. Moreover, a solid understanding of exception propagation can help prevent common pitfalls such as unhandled exceptions and resource leaks, which can lead to security vulnerabilities and poor user experiences. Candidates should also be aware of best practices in exception handling, including the use of specific exception types and avoiding excessive use of exceptions for control flow.

Sample Answers

Example 1: Basic Exception Propagation

When an exception occurs in a method, it can be caught and handled within that method. If it is not handled, the exception will propagate to the method that called it. For instance, consider the following code:

public void methodA() {
    methodB(); // Calls methodB
}

public void methodB() {
    throw new RuntimeException("Error in methodB"); // Exception thrown
}

In this example, methodB throws a RuntimeException. Since methodB does not handle this exception, it propagates back to methodA. If methodA also does not handle it, the exception will continue up the call stack. This propagation continues until it either reaches a catch block that handles it or the program terminates. Understanding this flow is essential to ensure that exceptions are handled appropriately at various levels of your application.

Example 2: Catching Exceptions at Different Levels

Consider a scenario where you have multiple layers in your application, like a controller calling a service method, which in turn calls a repository method. Here’s how exception propagation works:

public class Controller {
    public void handleRequest() {
        try {
            service.performAction();
        } catch (CustomException e) {
            // Handle exception
            System.out.println(e.getMessage());
        }
    }
}

public class Service {
    public void performAction() {
        repository.saveData();
    }
}

public class Repository {
    public void saveData() {
        throw new CustomException("Database error");
    }
}

In this case, the CustomException is thrown in the Repository class, but it is caught in the Controller class. This illustrates how exceptions can be propagated up through multiple layers, allowing for centralized error handling. This pattern is common in MVC architectures and helps maintain cleaner code by separating concerns.

Example 3: Handling Uncaught Exceptions

Uncaught exceptions can lead to application crashes, which is why it's essential to understand how to handle them. In many programming languages, you can set a global exception handler to catch any uncaught exceptions. For example, in Java, you can use:

public class Main {
    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            System.out.println("Unhandled exception: " + throwable.getMessage());
        });
        methodThatThrows();
    }

    public static void methodThatThrows() {
        throw new RuntimeException("Something went wrong");
    }
}

In this example, if methodThatThrows executes and throws an exception, the global handler captures it, allowing you to log the error or perform cleanup before the program terminates. This approach is critical for maintaining application stability and providing a better user experience, especially in production environments.

Keywords

exception handlingcall stackerror propagationsoftware engineeringresilience

Ready to practice more questions?

Explore our collection of technical interview questions from top companies.

View All Questions