Throwing Exceptions

Is this a totally valid / proper way of handling exceptions? For whatever reason I feel like this is improper
private String appendParametersToUrl(String url, String parameter, String string) throws IllegalArgumentException {
if (StringUtils.isBlank(parameter) || StringUtils.isBlank(string)) {
throw new IllegalArgumentException("Parameter or String arugments cannot be null.");
}

return ...;
}
private String appendParametersToUrl(String url, String parameter, String string) throws IllegalArgumentException {
if (StringUtils.isBlank(parameter) || StringUtils.isBlank(string)) {
throw new IllegalArgumentException("Parameter or String arugments cannot be null.");
}

return ...;
}
2 Replies
reddogg476
reddogg47610mo ago
Not fully, no. You're missing a catch block. Exceptions should be handled within the code or the application will fail. This is achieved with a try-catch block (in Javascript, C# and others). Some programming languages can handle thrown exception, but it is not good practice.
try {
if (StringUtils.isBlank(param) || StringUtils.isBlank(string) {
throw new IllegalArgumentException("Parameter or String arguments cannot be null.);
}
//function logic
}
catch (IllegalArgumentException except){
log(except.message)
}
try {
if (StringUtils.isBlank(param) || StringUtils.isBlank(string) {
throw new IllegalArgumentException("Parameter or String arguments cannot be null.);
}
//function logic
}
catch (IllegalArgumentException except){
log(except.message)
}
When you throw an exception, it is caught by the next catch block. If there's no catch block to catch the illegal argument - and the exception is terminating, -the program will terminate unexpectedly. Look at heading #5 in this blog. There may be multiple exceptions need caught: https://dzone.com/articles/9-best-practices-to-handle-exceptions-in-java
vince
vinceOP10mo ago
ty!!
Want results from more Discord servers?
Add your server