🌐
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.
🌐
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...
🌐
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....
🌐
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"); } } }
🌐
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 ...
🌐
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.
🌐
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()); } } } }
🌐
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.
Find elsewhere
🌐
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.
🌐
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:
🌐
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.
🌐
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.
🌐
Medium
medium.com › globant › best-practice-for-exception-handling-in-springboot-540484db8a1a
Best Practice for Exception Handling In SpringBoot | by Akash Bhingole | Globant | Medium
June 1, 2021 - In the below code snippet we see there are many duplications of lines as well the controller code is not able to be easily readable because of multiple try and catch blocks in each API. @RestController @RequestMapping(path = “/employees”) public class EmployeeController { private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class); private EmployeeDao employeeDao; @GetMapping(path=”/{employeeId}”, produces = “application/json”) public ResponseEntity<Employee> getEmployees(@PathVariable Long employeeId) { ResponseEntity<Employee> response = null; try { if(
Top answer
1 of 2
6

I've got a little problem with your exception handling. Principally it is absolutely ok to catch runtime exceptions, handle them and send them forth to the client, which is probably someone using your REST service and getting the error response as a JSON object. If you manage to tell him what he did wrong and what he can do about it, great! Of course, it will add some complexity to it, but it is probably easy and comfortable to work with that API.

But think about the backend developers, too, that work with your code. Especially the public User findById(Long id) method in your UserService is obscure. The reason for this is that you made your BusinessException, in particular, the UserNotFoundException unchecked.

If I joined your (backend) team, and I was to write some business logic using that service, I'd be quite sure what I had to expect from that method: I pass a user ID and get back a User object if it was found or null if not. That's why I would write code like that

User user = userService.findById("42A");
if (user == null) {
  // create a User or return an error or null or whatever
} else {
  // proceed
}

However, I would never know, that the first condition will never be true since you never return null. How should I know that I had to catch an Exception?

Is the compiler telling me to catch it? No, as it is not checked.

Would I look into your source code? Hell, no! Your case is extremely simple. That UserNotFoundException may be raised in another method in another class among hundred lines of code. Sometimes I couldn't look inside it, anyway, as that UserService is just a compiled class in a dependency.

Do I read the JavaDoc? Hahaha. Let's say, 50% of the time I wouldn't, and the other 50% you've forgotten to document it, anyway.

So, the developer has to wait until his code is used (either by a client or in Unit tests) to see that it doesn't work as he intended, forcing him to redesign what he has coded so far. And if your whole API is designed that way, that unchecked exceptions pop out of nowhere, it can be very very annoying, it costs time and money and is so easy to avoid, actually.

2 of 2
1

I use a similar way to handle exceptions. But in my case, different handlers are managed according to the error status (e.g. an user exists, an user cannot be registered due to some unsatisfied condition, etc.).

You also might add your generic BusinessException for some special cases. Hope it helps you feel better.

import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rest.restwebservices.controller.UserController;
import com.rest.restwebservices.exception.ResourceNotFoundException;
import com.rest.restwebservices.exception.PreconditionFailedException;
import com.rest.restwebservices.exception.ResourceAlreadyExistsException;
import com.rest.restwebservices.exception.fault.BusinessFault;

@ControllerAdvice(basePackageClasses = UserController.class)
public class BusinessExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseBody
    public ResponseEntity<BusinessFault> genericHandler(HttpServletRequest request, ResourceNotFoundException ex) {
        return new ResponseEntity<BusinessFault>(ex.getBusinessFault(), HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(PreconditionFailedException.class)
    @ResponseBody
    public ResponseEntity<BusinessFault> genericHandler(HttpServletRequest request, PreconditionFailedExceptionex) {
        return new ResponseEntity<BusinessFault>(ex.getBusinessFault(), HttpStatus.PRECONDITION_FAILED);
    }

    @ExceptionHandler(ResourceAlreadyExistsException.class)
    @ResponseBody
    public ResponseEntity<BusinessFault> genericHandler(HttpServletRequest request, ResourceAlreadyExistsException) {
        return new ResponseEntity<BusinessFault>(ex.getBusinessFault(), HttpStatus.CONFLICT);
    }
}
🌐
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....
🌐
Spring
spring.io › blog › 2013 › 11 › 01 › exception-handling-in-spring-mvc
Exception Handling in Spring MVC
Sadly Servlet 3 does not offer a Java API equivalent. Instead Spring Boot does the following: For a Jar application, with an embedded container, it registers a default error page using Container specific API. For a Spring Boot application deployed as a traditional WAR file, a Servlet Filter is used to · catch exceptions raised further down the line and handle it.
🌐
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.