Should I throw exceptions in an if-else block?
Here is the code:
public Response getABC(Request request) throws Exception {
Response res = new Response();
try {
if (request.someProperty == 1) {
// business logic
} else {
throw new Exception("xxxx");
}
} catch (Exception e) {
res.setMessage(e.getMessage); // I think this is weird
}
return res;
}
This program is working fine.
I think it should be redesigned, but how?
java
|
show 2 more comments
Here is the code:
public Response getABC(Request request) throws Exception {
Response res = new Response();
try {
if (request.someProperty == 1) {
// business logic
} else {
throw new Exception("xxxx");
}
} catch (Exception e) {
res.setMessage(e.getMessage); // I think this is weird
}
return res;
}
This program is working fine.
I think it should be redesigned, but how?
java
I don't think it is a good idea by throwing an exception in theelse
clause. byelse
, you should consider it a legal branch of your logic, which should not be anexception
– ZhaoGang
5 hours ago
2
Using exceptions for flow control is generally accepted as an anti pattern. Interestingly, thethrows Excetpion
(sic) declaration isn't needed.
– StuartLC
5 hours ago
1
I personally dislike using Exceptions for business flow.
– Sid
5 hours ago
1
@StuartLC: I would strongly disagree with that statement. It may be generally accepted in Java and C++ world, but some other languages embrace it - Python being a notable example:KeyError
orIndexError
on nonexistent index,StopIteration
at the end of an iterator,Http404
in Django to quickly abort the processing of a request and return a 404 NOT FOUND... The main problem with OP's code is that it is a useless exception, given that control-flow exceptions are used for non-local exits, while thatraise
is at kissing distance to itscatch
, as Eran says.
– Amadan
5 hours ago
1
@Amadan python is almost unique in that respect though. It's not just Java and C++.
– Jared Smith
18 mins ago
|
show 2 more comments
Here is the code:
public Response getABC(Request request) throws Exception {
Response res = new Response();
try {
if (request.someProperty == 1) {
// business logic
} else {
throw new Exception("xxxx");
}
} catch (Exception e) {
res.setMessage(e.getMessage); // I think this is weird
}
return res;
}
This program is working fine.
I think it should be redesigned, but how?
java
Here is the code:
public Response getABC(Request request) throws Exception {
Response res = new Response();
try {
if (request.someProperty == 1) {
// business logic
} else {
throw new Exception("xxxx");
}
} catch (Exception e) {
res.setMessage(e.getMessage); // I think this is weird
}
return res;
}
This program is working fine.
I think it should be redesigned, but how?
java
java
edited 52 mins ago
Pedro A
1,084925
1,084925
asked 5 hours ago
Vida Wang
885
885
I don't think it is a good idea by throwing an exception in theelse
clause. byelse
, you should consider it a legal branch of your logic, which should not be anexception
– ZhaoGang
5 hours ago
2
Using exceptions for flow control is generally accepted as an anti pattern. Interestingly, thethrows Excetpion
(sic) declaration isn't needed.
– StuartLC
5 hours ago
1
I personally dislike using Exceptions for business flow.
– Sid
5 hours ago
1
@StuartLC: I would strongly disagree with that statement. It may be generally accepted in Java and C++ world, but some other languages embrace it - Python being a notable example:KeyError
orIndexError
on nonexistent index,StopIteration
at the end of an iterator,Http404
in Django to quickly abort the processing of a request and return a 404 NOT FOUND... The main problem with OP's code is that it is a useless exception, given that control-flow exceptions are used for non-local exits, while thatraise
is at kissing distance to itscatch
, as Eran says.
– Amadan
5 hours ago
1
@Amadan python is almost unique in that respect though. It's not just Java and C++.
– Jared Smith
18 mins ago
|
show 2 more comments
I don't think it is a good idea by throwing an exception in theelse
clause. byelse
, you should consider it a legal branch of your logic, which should not be anexception
– ZhaoGang
5 hours ago
2
Using exceptions for flow control is generally accepted as an anti pattern. Interestingly, thethrows Excetpion
(sic) declaration isn't needed.
– StuartLC
5 hours ago
1
I personally dislike using Exceptions for business flow.
– Sid
5 hours ago
1
@StuartLC: I would strongly disagree with that statement. It may be generally accepted in Java and C++ world, but some other languages embrace it - Python being a notable example:KeyError
orIndexError
on nonexistent index,StopIteration
at the end of an iterator,Http404
in Django to quickly abort the processing of a request and return a 404 NOT FOUND... The main problem with OP's code is that it is a useless exception, given that control-flow exceptions are used for non-local exits, while thatraise
is at kissing distance to itscatch
, as Eran says.
– Amadan
5 hours ago
1
@Amadan python is almost unique in that respect though. It's not just Java and C++.
– Jared Smith
18 mins ago
I don't think it is a good idea by throwing an exception in the
else
clause. by else
, you should consider it a legal branch of your logic, which should not be an exception
– ZhaoGang
5 hours ago
I don't think it is a good idea by throwing an exception in the
else
clause. by else
, you should consider it a legal branch of your logic, which should not be an exception
– ZhaoGang
5 hours ago
2
2
Using exceptions for flow control is generally accepted as an anti pattern. Interestingly, the
throws Excetpion
(sic) declaration isn't needed.– StuartLC
5 hours ago
Using exceptions for flow control is generally accepted as an anti pattern. Interestingly, the
throws Excetpion
(sic) declaration isn't needed.– StuartLC
5 hours ago
1
1
I personally dislike using Exceptions for business flow.
– Sid
5 hours ago
I personally dislike using Exceptions for business flow.
– Sid
5 hours ago
1
1
@StuartLC: I would strongly disagree with that statement. It may be generally accepted in Java and C++ world, but some other languages embrace it - Python being a notable example:
KeyError
or IndexError
on nonexistent index, StopIteration
at the end of an iterator, Http404
in Django to quickly abort the processing of a request and return a 404 NOT FOUND... The main problem with OP's code is that it is a useless exception, given that control-flow exceptions are used for non-local exits, while that raise
is at kissing distance to its catch
, as Eran says.– Amadan
5 hours ago
@StuartLC: I would strongly disagree with that statement. It may be generally accepted in Java and C++ world, but some other languages embrace it - Python being a notable example:
KeyError
or IndexError
on nonexistent index, StopIteration
at the end of an iterator, Http404
in Django to quickly abort the processing of a request and return a 404 NOT FOUND... The main problem with OP's code is that it is a useless exception, given that control-flow exceptions are used for non-local exits, while that raise
is at kissing distance to its catch
, as Eran says.– Amadan
5 hours ago
1
1
@Amadan python is almost unique in that respect though. It's not just Java and C++.
– Jared Smith
18 mins ago
@Amadan python is almost unique in that respect though. It's not just Java and C++.
– Jared Smith
18 mins ago
|
show 2 more comments
5 Answers
5
active
oldest
votes
It makes no sense to throw an exception in a try block and immediately catch it, unless the catch block throws a different exception.
Your code would make more sense this way:
public Response getABC(Request request) {
Response res = new Response();
if (request.someProperty == 1) {
// business logic
} else {
res.setMessage(e.getMessage);
}
return res;
}
You only need the try-catch block if your business logic (executed when the condition is true
) may throw exceptions.
If you don't catch the exception (which means the caller will have to handle it), you can do without the else
clause:
public Response getABC(Request request) throws Exception {
if (request.someProperty != 1) {
throw new Exception("xxxx");
}
Response res = new Response();
// business logic
return res;
}
add a comment |
if you are throwing the exception from the method then why bother catching it ? it's either you return a response with "xxxx" message or throw an exception for the caller of this method to handle it.
public Response getABC(Request requst) {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}
return res;
}
OR
public Response getABC(Request requst) throw Excetpions {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
throw new Exception("xxxx");
}
return res;
}
public void someMethod(Request request) {
try {
Response r = getABC(request);
} catch (Exception e) {
//LOG exception or return response with error message
Response response = new Response();
response.setMessage("xxxx");
retunr response;
}
}
add a comment |
First and foremost, tread more carefully when you refactor a working method - especially if you are performing a manual refactoring. That said, introducing a variable to hold message
may be one way of changing the design:
public Response getABC(Request requst) throw Excetpions {
String message = "";
try{
if(request.someProperty == 1){
//business logic
else{
message = "xxxx";
}
}catch(Exception e){
message = e.getMessage();
}
Response res = new Response();
res.setMessage(message);
return res;
}
The assumption is that the business logic
does it's own return when it succeeds.
add a comment |
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, a have 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
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:
- Checked and unchecked exception
Java's checked exceptions were a mistake (Rod Waldhoff)
The Trouble with Checked Exceptions (Anders Hejlsberg)
add a comment |
it seems doesn't make sense when purposely throwing exception and then directly catch it,
it may redesign like this,
may change "throw new Exception("xxxx");" with "res.setMessage("xxxx");"
and then may keep catching the exception part in order to catch exception that may happen inside the business logic.
public Response getABC(Request requst) {
Response res = new Response();
try{
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}catch(Exception e){
res.setMessage(e.getMessage);
}
return res;
}
New contributor
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53941088%2fshould-i-throw-exceptions-in-an-if-else-block%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
It makes no sense to throw an exception in a try block and immediately catch it, unless the catch block throws a different exception.
Your code would make more sense this way:
public Response getABC(Request request) {
Response res = new Response();
if (request.someProperty == 1) {
// business logic
} else {
res.setMessage(e.getMessage);
}
return res;
}
You only need the try-catch block if your business logic (executed when the condition is true
) may throw exceptions.
If you don't catch the exception (which means the caller will have to handle it), you can do without the else
clause:
public Response getABC(Request request) throws Exception {
if (request.someProperty != 1) {
throw new Exception("xxxx");
}
Response res = new Response();
// business logic
return res;
}
add a comment |
It makes no sense to throw an exception in a try block and immediately catch it, unless the catch block throws a different exception.
Your code would make more sense this way:
public Response getABC(Request request) {
Response res = new Response();
if (request.someProperty == 1) {
// business logic
} else {
res.setMessage(e.getMessage);
}
return res;
}
You only need the try-catch block if your business logic (executed when the condition is true
) may throw exceptions.
If you don't catch the exception (which means the caller will have to handle it), you can do without the else
clause:
public Response getABC(Request request) throws Exception {
if (request.someProperty != 1) {
throw new Exception("xxxx");
}
Response res = new Response();
// business logic
return res;
}
add a comment |
It makes no sense to throw an exception in a try block and immediately catch it, unless the catch block throws a different exception.
Your code would make more sense this way:
public Response getABC(Request request) {
Response res = new Response();
if (request.someProperty == 1) {
// business logic
} else {
res.setMessage(e.getMessage);
}
return res;
}
You only need the try-catch block if your business logic (executed when the condition is true
) may throw exceptions.
If you don't catch the exception (which means the caller will have to handle it), you can do without the else
clause:
public Response getABC(Request request) throws Exception {
if (request.someProperty != 1) {
throw new Exception("xxxx");
}
Response res = new Response();
// business logic
return res;
}
It makes no sense to throw an exception in a try block and immediately catch it, unless the catch block throws a different exception.
Your code would make more sense this way:
public Response getABC(Request request) {
Response res = new Response();
if (request.someProperty == 1) {
// business logic
} else {
res.setMessage(e.getMessage);
}
return res;
}
You only need the try-catch block if your business logic (executed when the condition is true
) may throw exceptions.
If you don't catch the exception (which means the caller will have to handle it), you can do without the else
clause:
public Response getABC(Request request) throws Exception {
if (request.someProperty != 1) {
throw new Exception("xxxx");
}
Response res = new Response();
// business logic
return res;
}
edited 37 mins ago
Pedro A
1,084925
1,084925
answered 5 hours ago
Eran
279k37447534
279k37447534
add a comment |
add a comment |
if you are throwing the exception from the method then why bother catching it ? it's either you return a response with "xxxx" message or throw an exception for the caller of this method to handle it.
public Response getABC(Request requst) {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}
return res;
}
OR
public Response getABC(Request requst) throw Excetpions {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
throw new Exception("xxxx");
}
return res;
}
public void someMethod(Request request) {
try {
Response r = getABC(request);
} catch (Exception e) {
//LOG exception or return response with error message
Response response = new Response();
response.setMessage("xxxx");
retunr response;
}
}
add a comment |
if you are throwing the exception from the method then why bother catching it ? it's either you return a response with "xxxx" message or throw an exception for the caller of this method to handle it.
public Response getABC(Request requst) {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}
return res;
}
OR
public Response getABC(Request requst) throw Excetpions {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
throw new Exception("xxxx");
}
return res;
}
public void someMethod(Request request) {
try {
Response r = getABC(request);
} catch (Exception e) {
//LOG exception or return response with error message
Response response = new Response();
response.setMessage("xxxx");
retunr response;
}
}
add a comment |
if you are throwing the exception from the method then why bother catching it ? it's either you return a response with "xxxx" message or throw an exception for the caller of this method to handle it.
public Response getABC(Request requst) {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}
return res;
}
OR
public Response getABC(Request requst) throw Excetpions {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
throw new Exception("xxxx");
}
return res;
}
public void someMethod(Request request) {
try {
Response r = getABC(request);
} catch (Exception e) {
//LOG exception or return response with error message
Response response = new Response();
response.setMessage("xxxx");
retunr response;
}
}
if you are throwing the exception from the method then why bother catching it ? it's either you return a response with "xxxx" message or throw an exception for the caller of this method to handle it.
public Response getABC(Request requst) {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}
return res;
}
OR
public Response getABC(Request requst) throw Excetpions {
Response res = new Response();
if(request.someProperty == 1){
//business logic
else{
throw new Exception("xxxx");
}
return res;
}
public void someMethod(Request request) {
try {
Response r = getABC(request);
} catch (Exception e) {
//LOG exception or return response with error message
Response response = new Response();
response.setMessage("xxxx");
retunr response;
}
}
answered 5 hours ago
mkjh
1639
1639
add a comment |
add a comment |
First and foremost, tread more carefully when you refactor a working method - especially if you are performing a manual refactoring. That said, introducing a variable to hold message
may be one way of changing the design:
public Response getABC(Request requst) throw Excetpions {
String message = "";
try{
if(request.someProperty == 1){
//business logic
else{
message = "xxxx";
}
}catch(Exception e){
message = e.getMessage();
}
Response res = new Response();
res.setMessage(message);
return res;
}
The assumption is that the business logic
does it's own return when it succeeds.
add a comment |
First and foremost, tread more carefully when you refactor a working method - especially if you are performing a manual refactoring. That said, introducing a variable to hold message
may be one way of changing the design:
public Response getABC(Request requst) throw Excetpions {
String message = "";
try{
if(request.someProperty == 1){
//business logic
else{
message = "xxxx";
}
}catch(Exception e){
message = e.getMessage();
}
Response res = new Response();
res.setMessage(message);
return res;
}
The assumption is that the business logic
does it's own return when it succeeds.
add a comment |
First and foremost, tread more carefully when you refactor a working method - especially if you are performing a manual refactoring. That said, introducing a variable to hold message
may be one way of changing the design:
public Response getABC(Request requst) throw Excetpions {
String message = "";
try{
if(request.someProperty == 1){
//business logic
else{
message = "xxxx";
}
}catch(Exception e){
message = e.getMessage();
}
Response res = new Response();
res.setMessage(message);
return res;
}
The assumption is that the business logic
does it's own return when it succeeds.
First and foremost, tread more carefully when you refactor a working method - especially if you are performing a manual refactoring. That said, introducing a variable to hold message
may be one way of changing the design:
public Response getABC(Request requst) throw Excetpions {
String message = "";
try{
if(request.someProperty == 1){
//business logic
else{
message = "xxxx";
}
}catch(Exception e){
message = e.getMessage();
}
Response res = new Response();
res.setMessage(message);
return res;
}
The assumption is that the business logic
does it's own return when it succeeds.
answered 4 hours ago
Dakshinamurthy Karra
4,08311021
4,08311021
add a comment |
add a comment |
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, a have 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
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:
- Checked and unchecked exception
Java's checked exceptions were a mistake (Rod Waldhoff)
The Trouble with Checked Exceptions (Anders Hejlsberg)
add a comment |
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, a have 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
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:
- Checked and unchecked exception
Java's checked exceptions were a mistake (Rod Waldhoff)
The Trouble with Checked Exceptions (Anders Hejlsberg)
add a comment |
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, a have 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
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:
- Checked and unchecked exception
Java's checked exceptions were a mistake (Rod Waldhoff)
The Trouble with Checked Exceptions (Anders Hejlsberg)
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, a have 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
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:
- Checked and unchecked exception
Java's checked exceptions were a mistake (Rod Waldhoff)
The Trouble with Checked Exceptions (Anders Hejlsberg)
answered 3 hours ago
nhp
1,474414
1,474414
add a comment |
add a comment |
it seems doesn't make sense when purposely throwing exception and then directly catch it,
it may redesign like this,
may change "throw new Exception("xxxx");" with "res.setMessage("xxxx");"
and then may keep catching the exception part in order to catch exception that may happen inside the business logic.
public Response getABC(Request requst) {
Response res = new Response();
try{
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}catch(Exception e){
res.setMessage(e.getMessage);
}
return res;
}
New contributor
add a comment |
it seems doesn't make sense when purposely throwing exception and then directly catch it,
it may redesign like this,
may change "throw new Exception("xxxx");" with "res.setMessage("xxxx");"
and then may keep catching the exception part in order to catch exception that may happen inside the business logic.
public Response getABC(Request requst) {
Response res = new Response();
try{
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}catch(Exception e){
res.setMessage(e.getMessage);
}
return res;
}
New contributor
add a comment |
it seems doesn't make sense when purposely throwing exception and then directly catch it,
it may redesign like this,
may change "throw new Exception("xxxx");" with "res.setMessage("xxxx");"
and then may keep catching the exception part in order to catch exception that may happen inside the business logic.
public Response getABC(Request requst) {
Response res = new Response();
try{
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}catch(Exception e){
res.setMessage(e.getMessage);
}
return res;
}
New contributor
it seems doesn't make sense when purposely throwing exception and then directly catch it,
it may redesign like this,
may change "throw new Exception("xxxx");" with "res.setMessage("xxxx");"
and then may keep catching the exception part in order to catch exception that may happen inside the business logic.
public Response getABC(Request requst) {
Response res = new Response();
try{
if(request.someProperty == 1){
//business logic
else{
res.setMessage("xxxx");
}
}catch(Exception e){
res.setMessage(e.getMessage);
}
return res;
}
New contributor
edited 3 hours ago
New contributor
answered 4 hours ago
M Fauzan Abdi
365
365
New contributor
New contributor
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53941088%2fshould-i-throw-exceptions-in-an-if-else-block%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I don't think it is a good idea by throwing an exception in the
else
clause. byelse
, you should consider it a legal branch of your logic, which should not be anexception
– ZhaoGang
5 hours ago
2
Using exceptions for flow control is generally accepted as an anti pattern. Interestingly, the
throws Excetpion
(sic) declaration isn't needed.– StuartLC
5 hours ago
1
I personally dislike using Exceptions for business flow.
– Sid
5 hours ago
1
@StuartLC: I would strongly disagree with that statement. It may be generally accepted in Java and C++ world, but some other languages embrace it - Python being a notable example:
KeyError
orIndexError
on nonexistent index,StopIteration
at the end of an iterator,Http404
in Django to quickly abort the processing of a request and return a 404 NOT FOUND... The main problem with OP's code is that it is a useless exception, given that control-flow exceptions are used for non-local exits, while thatraise
is at kissing distance to itscatch
, as Eran says.– Amadan
5 hours ago
1
@Amadan python is almost unique in that respect though. It's not just Java and C++.
– Jared Smith
18 mins ago