Design exceptions to provide clear context, preserve stack traces, and propagate correctly through your system. Key practices include: 1. Choose the most appropriate exception type based on the error condition:
Design exceptions to provide clear context, preserve stack traces, and propagate correctly through your system. Key practices include:
IllegalArgumentException
for invalid inputsIllegalStateException
for invalid state// Poor practice
throw new ValidationException("Cannot unwrap to " + type);
// Better practice
throw new IllegalArgumentException("Cannot unwrap " + target + " to " + type.getName());
// Unnecessary wrapping
try {
this.jobLauncher.launch(job, jobParameters);
} catch (NoSuchJobException ex) {
throw new JobExecutionException(ex.getMessage(), ex);
}
// Better approach - NoSuchJobException is already a JobExecutionException
// Remove the try/catch completely
this.jobLauncher.launch(job, jobParameters);
catch (RuntimeException ex) {
try {
WebServer webServer = getWebServer();
if (webServer != null) {
webServer.stop();
}
}
catch (Exception shutdownEx) {
ex.addSuppressed(shutdownEx);
}
throw ex;
}
// Defensive (might mask issues)
Method initializeMethod = ReflectionUtils.findMethod(this.tester, "initialize", Class.class, ResolvableType.class);
if (initializeMethod == null) {
throw new IllegalStateException("unable to find initialize method for " + this.tester);
}
// Fail-fast (better for critical components)
Method initializeMethod = ReflectionUtils.findMethod(this.tester, "initialize", Class.class, ResolvableType.class);
// Let the NPE happen naturally if the method isn't found
// Errors suppressed:
webClient.post()
.bodyValue(body)
.retrieve()
.toBodilessEntity()
.subscribe((__) -> {}, (__) -> {});
// Proper error handling:
webClient.post()
.bodyValue(body)
.retrieve()
.toBodilessEntity()
.subscribe((__) -> {}, (error) -> errorHandler.handleError(error));
Enter the URL of a public GitHub repository