So I have various API endpoints defined in my Spring Boot services that throws various custom exceptions. But I am not able to make a distinction between Checked and Unchecked execptions.
So should my custom excpetion be checked or unchecked exception?
Examples:
- UserNotFoundException
- EmailAlreadyExistsException
- JWTTokenMalformedException
- DatabaseNodeFailureException
These exceptions are parserd by Springs controllerAdvice, converted to ResponseEntity and sent to client.
How would you define above custom created exceptions as checked or unchecked? Also let me know if there is any thumb rule to decide if your exception should be checked or unchecked?
CodePudding user response:
You are good even if you have all your exceptions as RuntimeException since you delegate error response generation to ControllerAdvice.
Regardless of whether it is a RESTful Spring Boot Service or just another Java Application the premise to throw Checked or Unchecked Exceptions from a method largely remains on whether the caller MUST (Checked) or SHALL (Runtime) handle exception.
For example when calling
FileInputStream fis = new FileInputStream("somefile.txt");
The constructor FileInputStream(String fileName) forces to handle the File not found exceptional scenario. Thus it throws a FileNotFoundException which is a checked exception and MUST be handled by the caller at the calling location itself.
CodePudding user response:
Also let me know if there is any thumb rule to decide if your exception should be Checked or Unchecked?
Checked Exception the compiler check and force you to handle the exception
Unchecked Exception the compiler does not warn you and you handle the exception by yourself
The rule you can adopt is the following
- if you are in a dependency case, where for instance you have to handle business rules throught many layers, then use
Checked Exception. It will force you to handle your exception in top layers (service > controller) - if you can't have the control on certain aspect of you application or architecture, such as access to a server or a file available in a location
Read this for more details.
