Why did you use try/catch statement when you already throw Checked Exception?
Checked exception is usually used in some languages like C++ or Java, but not in new language like Kotlin. I personally restrict to use it.
For example, I have a class like this:
class ApiService{
Response getSomething() throw Exception();
}
which feels clean and readable, but undermines the utility of the exception handling mechanism. Practically, getSomething()
doesn't offen throw checked exception but still need to behave as it does? This works when there is somebody upstream of ApiService who know how to deal with the unpredictable or unpreventable errors like this. And if you can really know how to deal with it, then go ahead and use something like the example below, otherwise, Unchecked Exception would be sufficient.
public Response getSomething(Request req) throws Exception{
if (req.someProperty == 1) {
Response res = new Response();
// logic
} else {
thows Exception("Some messages go here")
}
}
I will encourage to do in this way:
public Response getSomething(Request req){
if (req.someProperty == 1) {
Response res = new Response();
// logic
return res;
} else {
return ErrorResponse("error message"); // or throw RuntimeException here if you want to
}
}
For more insights, Kotlin
which I mentioned before doesn't support Checked exception because of many reasons.
The following is an example interface of the JDK
implemented by StringBuilder
class:
Appendable append(CharSequence csq) throws IOException;
What does this signature say? It says that every time I append a string to something (a StringBuilder
, some kind of a log, a console, etc.) I have to catch those IOExceptions
. Why? Because it might be performing IO
(Writer also implements Appendable
)… So it results into this kind of code all over the place:
try {
log.append(message)
}
catch (IOException e) {
// Must be safe
}
And this is no good, see Effective Java, 3rd Edition, Item 77: Don't ignore exceptions.
Take a look at these links:
else
clause. byelse
, you should consider it a legal branch of your logic, which should not be anexception
– Ikonthrows Excetpion
(sic) declaration isn't needed. – Accuse//business logic
? Can that code throw an exception that you need to catch inside this method? – Brunet.get
. – Blasiusthrows Exception
orcatch (Exception e)
, then you should probably refactor that first (regardless of the contents of this method!). You shouldn't accidentally catch aNullPointerException
, for that matter. So make the exception more specific, but not too specific: You should clearly point out (in the question) which (domain-specific) exception types you are dealing with there. – Bibby