Skip to content
  • errors vs Exceptions
  • Error are one which we can not handle
  • we can handle exceptions only
  • Compile time error
  • runtime error - this errors are exceptions
  • logical error - issue in logic no comiple time or runtime error
  • If you dont catch exception then program exectution stops
  • exception is thrown in form of object thats why we create Exception e in catch block
  • Hierarchy
  • Object -> Throwable -> error and Exception
    • Error -> ThreadDeath error, IO Error, OutOfMemory Error
    • Exceptions ->
  • NOte: only RunTimeExceptions are UnChecked Exception all other are checked exceptions. IDE/Java forces you to handle checked exceptions in code - RuntimeException (UnChecked Exception) = ArithMetic E, ArrayIndexOutOfBound E, NullPointer E, - SQLException = - IOException =
  • Custom exception, extends Exception class , create public constructor(String message) with super(message)

Spring Exception Handlingยถ

  • 3 ways to handle exception
  • Try catch with responseEntity in catch
  • Exception Handler - define in each controller with @Exceptionhander(NotFoundException.class)
  • RestControllerAdvice
  • Centralised -> InBuilt or Custom
  • when you do throw new NotFoundException("Product not found with ID: " + id); => and if you have not handled that globally then DispatcherServlet handles it

Annotataionsยถ

  • @ExceptionHandler(NotFoundException.class)
  • Today
  • @ExceptionHandler(NotFoundException.class) The snippet @ExceptionHandler(NotFoundException.class) is a Spring annotation used in Java applications to handle exceptions globally or at the controller level(defined the handler directly inside the controller class).
  • @ControllerAdvice
  • This approach centralizes exception handling across the entire application.

  • throw new ResponseStatusException( HttpStatus.NOT_FOUND, "User not found" ); -> Springโ€™s built-in exceptions for this you may not even need a custom handler for 404s because Spring handles it automatically.