Well it's up to developer to implement catch of exceptions mechanism. But it's a good practise to define exceptions types and error codes/messages for that. Let's say you have an endpoint which fetch product with id, but there is no product with that id, in that case client will receive http 500 code with internal server error message. This will confuse users and also developers, what was the real cause of that error.

So prevent those, you can get help from @ControllerAdvice annotation, which will allow to apply exception handlers to more than one or all controllers. First you will define your custom exceptions like :

public class ProductNotFoundException extends RuntimeException {

    public ProductNotFoundException(Long id) {

        super(String.format("Product with id %d not found", id));
    }
}

and then you can define your ControllerAdvice class:

@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {

 @ExceptionHandler(ProductNotFound.class)
    public ResponseEntity<Object> handleProductNotFoundException(
        ProductNotFoundException ex, WebRequest request) {

        Map<String, Object> body = new LinkedHashMap<>();
        body.put("timestamp", LocalDateTime.now());
        body.put("message", "Product not found");

        return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
    }
}
Answer from muhammed ozbilici on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › flow-control-in-try-catch-finally-in-java
Flow control in try catch finally in Java - GeeksforGeeks
July 23, 2025 - 3. Exception doesn't occur in try-block: In this case catch block never runs as they are only meant to be run when an exception occurs. finally block(if present) will be executed followed by rest of the program.
🌐
Apache Camel
camel.apache.org › apache camel › user manual › default › try, catch and finally
Try, Catch and Finally :: Apache Camel
<route> <from uri="direct:start"/> ... </doFinally> </doTry> </route> You can use Predicates with doCatch to make it runtime determine if the block should be triggered or not....
🌐
Quora
quora.com › What-is-the-difference-between-try-catch-and-ExceptionHandler-in-Java-Spring-Boot
What is the difference between try-catch and @ExceptionHandler in Java/Spring Boot? - Quora
Answer (1 of 3): Spring consider exception handling a cross-cutting concern, thus it allows you to handle exceptions separately from the rest of your code. This approach truly does work great with Spring! Imagine that you have an http endpoints in your application but in order to access it, a va...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-try-catch-block
Java Try Catch Block - GeeksforGeeks
June 3, 2025 - import java.util.*; public class Geeks { public static void main(String[] args) { try { // Outer try block System.out.println("Outer try block started"); try { // Inner try block 1 int n = 10; int res = n / 0; } catch (ArithmeticException e) { System.out.println ("Caught ArithmeticException in inner try-catch: " + e); } try { // Inner try block 2 String s = null; System.out.println(s.length()); } catch (NullPointerException e) { System.out.println ("Caught NullPointerException in inner try-catch: " + e); } } catch (Exception e) { // Outer catch block System.out.println ("Caught exception in outer try-catch: " + e); } finally { // Finally block System.out.println("Finally block executed"); } } }
🌐
CodeJava
codejava.net › java-core › exception › what-you-may-not-know-about-the-try-catch-finally-construct-in-java
What you may not know about the try-catch-finally construct in Java
[Master REST API Development and Java and Spring Boot] This Java tutorial demystifies the try-catch-finally construct in Java programming language.
🌐
Java Guides
javaguides.net › 2018 › 08 › java-trycatch-block.html
Java try/catch Block
June 21, 2024 - Nested try/catch: Inner catch: Arithmetic error: / by zero Nested try/catch: Outer catch: Array index out of bounds: Index 10 out of bounds for length 3 · The try/catch block in Java is a fundamental construct for handling exceptions.
🌐
Davidgiard
davidgiard.com › throwing-and-catching-custom-exceptions-in-a-java-spring-boot-application
Throwing and Catching Custom Exceptions in a Java Spring Boot Application
Finally, we modify our controller method, wrapping the call to the service in a try/catch structure and returning an error HTTP code and error message only if the exception is caught in the catch block, as shown below:
Find elsewhere
🌐
Davidgiard
davidgiard.com › more-error-handling-in-a-spring-boot-application
More Error Handling in a Spring Boot Application
The first CATCH block will trap an Arithmetic error, which is what happens we try to divide by 0. The second CATCH block traps any other errors that occur. With this code change, the results are more useful when a client passes a 0 as a denominator, as shown in Fig. 3. ... This article shows an example of gracefully handling errors in a Java Spring Boot REST API.
🌐
Baeldung
baeldung.com › home › java › core java › exception handling in java
Exception Handling in Java | Baeldung
May 11, 2024 - If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded). Similar to using return in a finally block, the exception thrown in a finally block will take precedence ...
🌐
Medium
medium.com › @aravindcsebe › complete-guide-to-exception-handling-in-java-and-spring-boot-197e46a6747d
Complete Guide to Exception Handling in Java and Spring Boot | by Aravindcsebe | Oct, 2025 | Medium
October 3, 2025 - public void tryCatchFinally() { FileInputStream file = null; try { file = new FileInputStream("data.txt"); // Process file int data = file.read(); } catch (FileNotFoundException e) { System.err.println("File not found: " + e.getMessage()); } catch (IOException e) { System.err.println("IO Error: " + e.getMessage()); } finally { // This block always executes if (file != null) { try { file.close(); } catch (IOException e) { System.err.println("Error closing file: " + e.getMessage()); } } } }
🌐
DEV Community
dev.to › sharique_siddiqui_8242dad › exception-handling-for-beginners-try-catch-finally-in-java-3o46
Exception Handling for Beginners: try, catch, finally in Java - DEV Community
August 7, 2025 - 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. 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.
🌐
Medium
medium.com › @mariorodrguezgalicia › exception-handling-from-java-fundamentals-to-implementation-in-spring-boot-part-ii-5eba3bb817b4
Exception Handling: From Java Basics to Implementation in Spring Boot — Part II | by Mario Rodríguez | Medium
July 8, 2025 - If you try to define an ... context of the DispatcherServlet. To handle an exception inside a service, you would have to use a try-catch, but this is neither practical nor scalable....
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String Methods
🌐
DZone
dzone.com › coding › frameworks › best practice for exception handling in spring boot
Best Practices: Exception Handling In Spring Boot
September 2, 2020 - Under this class, we make use of annotations provided as @ExceptionHandler, @ModelAttribute, @InitBinder. Review a guide covering all Spring Boot Annotations. Exception handling methods annotated with @ExceptionHandler will catch the exception thrown by the declared class and we can perform various things whenever we come through the related type exceptions.
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java finally keyword
Guide to the Java finally Keyword | Baeldung
January 16, 2024 - In this tutorial, we’ll explore the finally keyword in Java. We’ll see how to use it alongside try/catch blocks in error handling.
🌐
Doubleslash
blog.doubleslash.de › home page › software technologies › bad practice: swallowing the source exception with catch/finally
Bad practice: Swallowing the original exception at catch/finally - Business - Software and IT Blog - We shape digital value creation
April 11, 2025 - As we can see: In both cases, the original exception is swallowed up. This is misleading and makes troubleshooting much more difficult. But how can we do better? The rest of the article presents the following three possible solutions: Catching and logging the exception that occurs in the Finally or Catch block
Top answer
1 of 2
150

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

2 of 2
107

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally
🌐
Reflectoring
reflectoring.io › spring-boot-exception-handling
Complete Guide to Exception Handling in Spring Boot
December 31, 2020 - We can skip logging on field validation exceptions such as MethodArgumentNotValidException as they are raised because of syntactically invalid input, but we should always log unknown exceptions in the catch-all handler. The order in which you mention the handler methods doesn’t matter. Spring will first look for the most specific exception handler method. If it fails to find it then it will look for a handler of the parent exception, which in our case is RuntimeException, and if none is found, the handleAllUncaughtException() method will finally handle the exception.