Catching generic Exception in a toString implementation - bad practice?When to use StringBuilder in JavaJava - overriding Object's toString() method, but I have to throw exceptionsCatch multiple exceptions at once?The case against checked exceptionsGlobally catch exceptions in a WPF application?Can I catch multiple Java exceptions in the same catch clause?Catch multiple exceptions in one line (except block)The Use of Multiple JFrames: Good or Bad Practice?java - In java, why is Exception the base class and not RuntimeException?Why is “except: pass” a bad programming practice?Which part of throwing an Exception is expensive?Is catching generic exception in DAO layer a bad practice?
What was the first science fiction or fantasy multiple choice book?
Meaning of the word "good" in context
Early 2000s movie about time travel, protagonist travels back to save girlfriend, then into multiple points in future
Russian equivalents of 能骗就骗 (if you can cheat, then cheat)
Why will we fail creating a self sustaining off world colony?
Why do some PCBs have exposed plated perimeters?
How to count the number of bytes in a file, grouping the same bytes?
Is leaving out prefixes like "rauf", "rüber", "rein" when describing movement considered a big mistake in spoken German?
Avoiding repetition when using the "snprintf idiom" to write text
Having to constantly redo everything because I don't know how to do it
Why was Pan Am Flight 103 flying over Lockerbie?
Calculus, water poured into a cone: Why is the derivative non-linear?
Is it OK to throw pebbles and stones in streams, waterfalls, ponds, etc.?
Journal standards vs. personal standards
What does 'in attendance' mean on an England death certificate?
he and she - er und sie
Why am I getting an electric shock from the water in my hot tub?
Why should I allow multiple IPs on a website for a single session?
Why is my 401k manager recommending me to save more?
Word ending in "-ine" for rat-like
What verb for taking advantage fits in "I don't want to ________ on the friendship"?
Why are symbols not written in words?
Why would Dementors torture a Death Eater if they are loyal to Voldemort?
Is my guitar action too high or is the bridge too high?
Catching generic Exception in a toString implementation - bad practice?
When to use StringBuilder in JavaJava - overriding Object's toString() method, but I have to throw exceptionsCatch multiple exceptions at once?The case against checked exceptionsGlobally catch exceptions in a WPF application?Can I catch multiple Java exceptions in the same catch clause?Catch multiple exceptions in one line (except block)The Use of Multiple JFrames: Good or Bad Practice?java - In java, why is Exception the base class and not RuntimeException?Why is “except: pass” a bad programming practice?Which part of throwing an Exception is expensive?Is catching generic exception in DAO layer a bad practice?
I have a domain model class which has a toString implementation that looks like this:
public String toString()
try
return getX() + "n"
getY() + "n"
getZ(); //etc.
catch(Exception e)
throw new RuntimeException(e);
The methods getX()
, getY()
and getZ()
are not simple getters, they can perform lookups in the background, generally a lookup to a static map of predefined key-value pairs. Some of them had throws SomeCheckedException
in their signatures.
My impression is that this is bad practice and a "code smell". The fact that toString()
even needs this check is to me a symptom of bad design. But I'm asked by a colleague, what exactly is wrong with catching the generic Exception
in a toString()
, since the caught Exception
is propagated further.
I believe it violates at least the KISS principle, since a simple method like toString()
here is indicated as requiring special exception handling.
So is it code smell to have a catch-all block in a toString()?
Answers I found were either for the general scenario of catching generic Exception
and I agree with most of them, that if you're doing a generic error handling mechanism or a batch then it's expected to work on generic exceptions. This argument was unconvincing in our discussion, so I'm curious of other opinions.
java exception tostring
add a comment |
I have a domain model class which has a toString implementation that looks like this:
public String toString()
try
return getX() + "n"
getY() + "n"
getZ(); //etc.
catch(Exception e)
throw new RuntimeException(e);
The methods getX()
, getY()
and getZ()
are not simple getters, they can perform lookups in the background, generally a lookup to a static map of predefined key-value pairs. Some of them had throws SomeCheckedException
in their signatures.
My impression is that this is bad practice and a "code smell". The fact that toString()
even needs this check is to me a symptom of bad design. But I'm asked by a colleague, what exactly is wrong with catching the generic Exception
in a toString()
, since the caught Exception
is propagated further.
I believe it violates at least the KISS principle, since a simple method like toString()
here is indicated as requiring special exception handling.
So is it code smell to have a catch-all block in a toString()?
Answers I found were either for the general scenario of catching generic Exception
and I agree with most of them, that if you're doing a generic error handling mechanism or a batch then it's expected to work on generic exceptions. This argument was unconvincing in our discussion, so I'm curious of other opinions.
java exception tostring
2
I'd consider it somewhat bad practice to do more that simple getter calls fortoString()
actually. If you require some kind of lookup, you should describe the lookup rather than perform it.
– daniu
Jun 21 at 16:51
add a comment |
I have a domain model class which has a toString implementation that looks like this:
public String toString()
try
return getX() + "n"
getY() + "n"
getZ(); //etc.
catch(Exception e)
throw new RuntimeException(e);
The methods getX()
, getY()
and getZ()
are not simple getters, they can perform lookups in the background, generally a lookup to a static map of predefined key-value pairs. Some of them had throws SomeCheckedException
in their signatures.
My impression is that this is bad practice and a "code smell". The fact that toString()
even needs this check is to me a symptom of bad design. But I'm asked by a colleague, what exactly is wrong with catching the generic Exception
in a toString()
, since the caught Exception
is propagated further.
I believe it violates at least the KISS principle, since a simple method like toString()
here is indicated as requiring special exception handling.
So is it code smell to have a catch-all block in a toString()?
Answers I found were either for the general scenario of catching generic Exception
and I agree with most of them, that if you're doing a generic error handling mechanism or a batch then it's expected to work on generic exceptions. This argument was unconvincing in our discussion, so I'm curious of other opinions.
java exception tostring
I have a domain model class which has a toString implementation that looks like this:
public String toString()
try
return getX() + "n"
getY() + "n"
getZ(); //etc.
catch(Exception e)
throw new RuntimeException(e);
The methods getX()
, getY()
and getZ()
are not simple getters, they can perform lookups in the background, generally a lookup to a static map of predefined key-value pairs. Some of them had throws SomeCheckedException
in their signatures.
My impression is that this is bad practice and a "code smell". The fact that toString()
even needs this check is to me a symptom of bad design. But I'm asked by a colleague, what exactly is wrong with catching the generic Exception
in a toString()
, since the caught Exception
is propagated further.
I believe it violates at least the KISS principle, since a simple method like toString()
here is indicated as requiring special exception handling.
So is it code smell to have a catch-all block in a toString()?
Answers I found were either for the general scenario of catching generic Exception
and I agree with most of them, that if you're doing a generic error handling mechanism or a batch then it's expected to work on generic exceptions. This argument was unconvincing in our discussion, so I'm curious of other opinions.
java exception tostring
java exception tostring
edited Jun 21 at 20:26
Derefacto
8122 silver badges19 bronze badges
8122 silver badges19 bronze badges
asked Jun 21 at 16:21
generickycdevelopergenerickycdeveloper
413 bronze badges
413 bronze badges
2
I'd consider it somewhat bad practice to do more that simple getter calls fortoString()
actually. If you require some kind of lookup, you should describe the lookup rather than perform it.
– daniu
Jun 21 at 16:51
add a comment |
2
I'd consider it somewhat bad practice to do more that simple getter calls fortoString()
actually. If you require some kind of lookup, you should describe the lookup rather than perform it.
– daniu
Jun 21 at 16:51
2
2
I'd consider it somewhat bad practice to do more that simple getter calls for
toString()
actually. If you require some kind of lookup, you should describe the lookup rather than perform it.– daniu
Jun 21 at 16:51
I'd consider it somewhat bad practice to do more that simple getter calls for
toString()
actually. If you require some kind of lookup, you should describe the lookup rather than perform it.– daniu
Jun 21 at 16:51
add a comment |
4 Answers
4
active
oldest
votes
Yes this is bad practice.
The intention of the toString method is to provide a programmer readable representation of your class. You shouldn't include any method calls in this method, including getters.
In fact, I would consider not autogenerating these methods smelly, but assuming you are not comfortable or able to use an IDE that would produce them for you, I would recommend including a reference to all the fields on the object, and the class name of the object, as is done by the intellij toString method
1
There is no reason to use a StringBuilder in place of a one-line concatenation. It makes the code harder to read while providing no benefit.
– VGR
Jun 21 at 20:21
and yet some people like and use it. :shrug:
– Maus
Jun 21 at 20:23
1
huh: I'll edit my answer to remove that line: stackoverflow.com/questions/4645020/…
– Maus
Jun 21 at 20:24
add a comment |
The main reason not to catch generic Exception at any place is that it will include RuntimeExceptions too, which should not be catched on normal circumstances, because they always represent a bug in the program. It's better to let them be propagated and arise, so that the developer can notice it and eventually fix it.
I don't know if any additional good practice checks shall be applied in the case of toString
methods, but I'm sure at least the general rule should be applied.
So, the best practice is always to catch only checked exceptions, and then either recover, either rethrow them, or either rewrap them into another exception (which is your case).
add a comment |
For the toString()
method, catching Exception
is not necessarily a bad practice. However, re-throwing it is the problematic part.
The contract for toString() is:
... In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read...
In Effective Java 3rd Edition (Item 12), Bloch further insists:
When practical, the toString method should return all of the interesting information contained in the object.
So, if this requires calling methods that may throw checked exceptions, then so be it, and it makes a lot of sense to catch these exceptions.
However: raised checked exceptions provide information about the state of the object. Consistently with the goal of toString
, it may be a good idea to include the exceptional condition in the message returned by toString
.
As for why it's a bad idea to throw exceptions from toString
, this post provides a great answer.
Recommendation: Catch the checked exceptions using their specific exception type, and integrate this fact in the toString()
message, instead of propagating it.
add a comment |
Should the "normal flow" be interrupted by a failing toString() method? If the answer is no, you should make the toString() method "work". Catching an exception an reflecting this in the result is one possibility, or a simple log output.
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%2f56707201%2fcatching-generic-exception-in-a-tostring-implementation-bad-practice%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Yes this is bad practice.
The intention of the toString method is to provide a programmer readable representation of your class. You shouldn't include any method calls in this method, including getters.
In fact, I would consider not autogenerating these methods smelly, but assuming you are not comfortable or able to use an IDE that would produce them for you, I would recommend including a reference to all the fields on the object, and the class name of the object, as is done by the intellij toString method
1
There is no reason to use a StringBuilder in place of a one-line concatenation. It makes the code harder to read while providing no benefit.
– VGR
Jun 21 at 20:21
and yet some people like and use it. :shrug:
– Maus
Jun 21 at 20:23
1
huh: I'll edit my answer to remove that line: stackoverflow.com/questions/4645020/…
– Maus
Jun 21 at 20:24
add a comment |
Yes this is bad practice.
The intention of the toString method is to provide a programmer readable representation of your class. You shouldn't include any method calls in this method, including getters.
In fact, I would consider not autogenerating these methods smelly, but assuming you are not comfortable or able to use an IDE that would produce them for you, I would recommend including a reference to all the fields on the object, and the class name of the object, as is done by the intellij toString method
1
There is no reason to use a StringBuilder in place of a one-line concatenation. It makes the code harder to read while providing no benefit.
– VGR
Jun 21 at 20:21
and yet some people like and use it. :shrug:
– Maus
Jun 21 at 20:23
1
huh: I'll edit my answer to remove that line: stackoverflow.com/questions/4645020/…
– Maus
Jun 21 at 20:24
add a comment |
Yes this is bad practice.
The intention of the toString method is to provide a programmer readable representation of your class. You shouldn't include any method calls in this method, including getters.
In fact, I would consider not autogenerating these methods smelly, but assuming you are not comfortable or able to use an IDE that would produce them for you, I would recommend including a reference to all the fields on the object, and the class name of the object, as is done by the intellij toString method
Yes this is bad practice.
The intention of the toString method is to provide a programmer readable representation of your class. You shouldn't include any method calls in this method, including getters.
In fact, I would consider not autogenerating these methods smelly, but assuming you are not comfortable or able to use an IDE that would produce them for you, I would recommend including a reference to all the fields on the object, and the class name of the object, as is done by the intellij toString method
edited Jun 21 at 20:24
answered Jun 21 at 16:50
MausMaus
1,0951 gold badge10 silver badges25 bronze badges
1,0951 gold badge10 silver badges25 bronze badges
1
There is no reason to use a StringBuilder in place of a one-line concatenation. It makes the code harder to read while providing no benefit.
– VGR
Jun 21 at 20:21
and yet some people like and use it. :shrug:
– Maus
Jun 21 at 20:23
1
huh: I'll edit my answer to remove that line: stackoverflow.com/questions/4645020/…
– Maus
Jun 21 at 20:24
add a comment |
1
There is no reason to use a StringBuilder in place of a one-line concatenation. It makes the code harder to read while providing no benefit.
– VGR
Jun 21 at 20:21
and yet some people like and use it. :shrug:
– Maus
Jun 21 at 20:23
1
huh: I'll edit my answer to remove that line: stackoverflow.com/questions/4645020/…
– Maus
Jun 21 at 20:24
1
1
There is no reason to use a StringBuilder in place of a one-line concatenation. It makes the code harder to read while providing no benefit.
– VGR
Jun 21 at 20:21
There is no reason to use a StringBuilder in place of a one-line concatenation. It makes the code harder to read while providing no benefit.
– VGR
Jun 21 at 20:21
and yet some people like and use it. :shrug:
– Maus
Jun 21 at 20:23
and yet some people like and use it. :shrug:
– Maus
Jun 21 at 20:23
1
1
huh: I'll edit my answer to remove that line: stackoverflow.com/questions/4645020/…
– Maus
Jun 21 at 20:24
huh: I'll edit my answer to remove that line: stackoverflow.com/questions/4645020/…
– Maus
Jun 21 at 20:24
add a comment |
The main reason not to catch generic Exception at any place is that it will include RuntimeExceptions too, which should not be catched on normal circumstances, because they always represent a bug in the program. It's better to let them be propagated and arise, so that the developer can notice it and eventually fix it.
I don't know if any additional good practice checks shall be applied in the case of toString
methods, but I'm sure at least the general rule should be applied.
So, the best practice is always to catch only checked exceptions, and then either recover, either rethrow them, or either rewrap them into another exception (which is your case).
add a comment |
The main reason not to catch generic Exception at any place is that it will include RuntimeExceptions too, which should not be catched on normal circumstances, because they always represent a bug in the program. It's better to let them be propagated and arise, so that the developer can notice it and eventually fix it.
I don't know if any additional good practice checks shall be applied in the case of toString
methods, but I'm sure at least the general rule should be applied.
So, the best practice is always to catch only checked exceptions, and then either recover, either rethrow them, or either rewrap them into another exception (which is your case).
add a comment |
The main reason not to catch generic Exception at any place is that it will include RuntimeExceptions too, which should not be catched on normal circumstances, because they always represent a bug in the program. It's better to let them be propagated and arise, so that the developer can notice it and eventually fix it.
I don't know if any additional good practice checks shall be applied in the case of toString
methods, but I'm sure at least the general rule should be applied.
So, the best practice is always to catch only checked exceptions, and then either recover, either rethrow them, or either rewrap them into another exception (which is your case).
The main reason not to catch generic Exception at any place is that it will include RuntimeExceptions too, which should not be catched on normal circumstances, because they always represent a bug in the program. It's better to let them be propagated and arise, so that the developer can notice it and eventually fix it.
I don't know if any additional good practice checks shall be applied in the case of toString
methods, but I'm sure at least the general rule should be applied.
So, the best practice is always to catch only checked exceptions, and then either recover, either rethrow them, or either rewrap them into another exception (which is your case).
answered Jun 21 at 16:32
Little SantiLittle Santi
7,0042 gold badges11 silver badges34 bronze badges
7,0042 gold badges11 silver badges34 bronze badges
add a comment |
add a comment |
For the toString()
method, catching Exception
is not necessarily a bad practice. However, re-throwing it is the problematic part.
The contract for toString() is:
... In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read...
In Effective Java 3rd Edition (Item 12), Bloch further insists:
When practical, the toString method should return all of the interesting information contained in the object.
So, if this requires calling methods that may throw checked exceptions, then so be it, and it makes a lot of sense to catch these exceptions.
However: raised checked exceptions provide information about the state of the object. Consistently with the goal of toString
, it may be a good idea to include the exceptional condition in the message returned by toString
.
As for why it's a bad idea to throw exceptions from toString
, this post provides a great answer.
Recommendation: Catch the checked exceptions using their specific exception type, and integrate this fact in the toString()
message, instead of propagating it.
add a comment |
For the toString()
method, catching Exception
is not necessarily a bad practice. However, re-throwing it is the problematic part.
The contract for toString() is:
... In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read...
In Effective Java 3rd Edition (Item 12), Bloch further insists:
When practical, the toString method should return all of the interesting information contained in the object.
So, if this requires calling methods that may throw checked exceptions, then so be it, and it makes a lot of sense to catch these exceptions.
However: raised checked exceptions provide information about the state of the object. Consistently with the goal of toString
, it may be a good idea to include the exceptional condition in the message returned by toString
.
As for why it's a bad idea to throw exceptions from toString
, this post provides a great answer.
Recommendation: Catch the checked exceptions using their specific exception type, and integrate this fact in the toString()
message, instead of propagating it.
add a comment |
For the toString()
method, catching Exception
is not necessarily a bad practice. However, re-throwing it is the problematic part.
The contract for toString() is:
... In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read...
In Effective Java 3rd Edition (Item 12), Bloch further insists:
When practical, the toString method should return all of the interesting information contained in the object.
So, if this requires calling methods that may throw checked exceptions, then so be it, and it makes a lot of sense to catch these exceptions.
However: raised checked exceptions provide information about the state of the object. Consistently with the goal of toString
, it may be a good idea to include the exceptional condition in the message returned by toString
.
As for why it's a bad idea to throw exceptions from toString
, this post provides a great answer.
Recommendation: Catch the checked exceptions using their specific exception type, and integrate this fact in the toString()
message, instead of propagating it.
For the toString()
method, catching Exception
is not necessarily a bad practice. However, re-throwing it is the problematic part.
The contract for toString() is:
... In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read...
In Effective Java 3rd Edition (Item 12), Bloch further insists:
When practical, the toString method should return all of the interesting information contained in the object.
So, if this requires calling methods that may throw checked exceptions, then so be it, and it makes a lot of sense to catch these exceptions.
However: raised checked exceptions provide information about the state of the object. Consistently with the goal of toString
, it may be a good idea to include the exceptional condition in the message returned by toString
.
As for why it's a bad idea to throw exceptions from toString
, this post provides a great answer.
Recommendation: Catch the checked exceptions using their specific exception type, and integrate this fact in the toString()
message, instead of propagating it.
answered Jun 21 at 19:02
DerefactoDerefacto
8122 silver badges19 bronze badges
8122 silver badges19 bronze badges
add a comment |
add a comment |
Should the "normal flow" be interrupted by a failing toString() method? If the answer is no, you should make the toString() method "work". Catching an exception an reflecting this in the result is one possibility, or a simple log output.
add a comment |
Should the "normal flow" be interrupted by a failing toString() method? If the answer is no, you should make the toString() method "work". Catching an exception an reflecting this in the result is one possibility, or a simple log output.
add a comment |
Should the "normal flow" be interrupted by a failing toString() method? If the answer is no, you should make the toString() method "work". Catching an exception an reflecting this in the result is one possibility, or a simple log output.
Should the "normal flow" be interrupted by a failing toString() method? If the answer is no, you should make the toString() method "work". Catching an exception an reflecting this in the result is one possibility, or a simple log output.
answered Jun 21 at 20:32
KoWKoW
5943 silver badges12 bronze badges
5943 silver badges12 bronze badges
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.
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%2f56707201%2fcatching-generic-exception-in-a-tostring-implementation-bad-practice%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
2
I'd consider it somewhat bad practice to do more that simple getter calls for
toString()
actually. If you require some kind of lookup, you should describe the lookup rather than perform it.– daniu
Jun 21 at 16:51