Is it really that bad to catch a general exception?
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
exception
add a comment |
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
exception
2
If input is not predictable, and failure is not an option - it's the only way. Of course, there is no good reason not to LOG the error so that it can be properly handled the next time.
– mehtunguh
Dec 2 '12 at 1:59
1
Is this a question that would be better suited to programmers.stackexchange?
– HardcoreBro
Nov 22 '13 at 16:13
I love that this is also called "Pokémon catch — gotta catch 'em all".
– Uwe Keim
Aug 16 '16 at 6:54
Duplicate on SE.SE: Is catching general exceptions really a bad thing?
– jrh
Jun 11 at 17:31
add a comment |
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
exception
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
exception
exception
asked Aug 22 '08 at 7:41
Triss
2872511
2872511
2
If input is not predictable, and failure is not an option - it's the only way. Of course, there is no good reason not to LOG the error so that it can be properly handled the next time.
– mehtunguh
Dec 2 '12 at 1:59
1
Is this a question that would be better suited to programmers.stackexchange?
– HardcoreBro
Nov 22 '13 at 16:13
I love that this is also called "Pokémon catch — gotta catch 'em all".
– Uwe Keim
Aug 16 '16 at 6:54
Duplicate on SE.SE: Is catching general exceptions really a bad thing?
– jrh
Jun 11 at 17:31
add a comment |
2
If input is not predictable, and failure is not an option - it's the only way. Of course, there is no good reason not to LOG the error so that it can be properly handled the next time.
– mehtunguh
Dec 2 '12 at 1:59
1
Is this a question that would be better suited to programmers.stackexchange?
– HardcoreBro
Nov 22 '13 at 16:13
I love that this is also called "Pokémon catch — gotta catch 'em all".
– Uwe Keim
Aug 16 '16 at 6:54
Duplicate on SE.SE: Is catching general exceptions really a bad thing?
– jrh
Jun 11 at 17:31
2
2
If input is not predictable, and failure is not an option - it's the only way. Of course, there is no good reason not to LOG the error so that it can be properly handled the next time.
– mehtunguh
Dec 2 '12 at 1:59
If input is not predictable, and failure is not an option - it's the only way. Of course, there is no good reason not to LOG the error so that it can be properly handled the next time.
– mehtunguh
Dec 2 '12 at 1:59
1
1
Is this a question that would be better suited to programmers.stackexchange?
– HardcoreBro
Nov 22 '13 at 16:13
Is this a question that would be better suited to programmers.stackexchange?
– HardcoreBro
Nov 22 '13 at 16:13
I love that this is also called "Pokémon catch — gotta catch 'em all".
– Uwe Keim
Aug 16 '16 at 6:54
I love that this is also called "Pokémon catch — gotta catch 'em all".
– Uwe Keim
Aug 16 '16 at 6:54
Duplicate on SE.SE: Is catching general exceptions really a bad thing?
– jrh
Jun 11 at 17:31
Duplicate on SE.SE: Is catching general exceptions really a bad thing?
– jrh
Jun 11 at 17:31
add a comment |
14 Answers
14
active
oldest
votes
Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
7
Catching all exceptions at language borders to translate them is also good practice.
– Alexandre C.
Aug 3 '11 at 16:12
"The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" " The funny thing is, the .NET framework actually catchesOutOfMemoryException
sometimes.
– jrh
Jun 11 at 17:29
add a comment |
Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
add a comment |
Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
1
The catch could be used to add additional information and then rethrow, right?
– Maarten Bodewes
Sep 7 '16 at 14:50
add a comment |
In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
add a comment |
There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
7
Letting an exception bubble up does not mean showing it to the end user. You can (and should) show a generic error page, log it for investigation, and then fix the problem that caused the exception in the first place.
– jammycakes
Apr 20 '09 at 8:52
2
Does not answer question asked.
– Kenneth K.
Feb 12 '16 at 13:47
add a comment |
Well, I don't seen any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
You will catch both IOException and NullPointerException with a generic Exception, but the way you program should react is probably different.
add a comment |
The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
It is bad to code logic by exceptions, if you expect that file provided by user could not exist, there is a method to check that: File.exists().
– Krzysztof Cichocki
Jun 27 '16 at 11:02
@KrzysztofCichocki - I know this is old, but actually, coding file logic using exceptions in this way is more correct. There's a great explanation by Eric Lippert here. He terms this type "exogenous" exceptions.
– Olly
Jul 4 '17 at 15:35
add a comment |
The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
What would happen if the code which calledCriticalException
also calledThread.Abort(Thread.CurrentThread)
? Because the thread being aborted would be in a known state (callingAbort
), the normal hazards of that method wouldn't apply; code which does acatch(Exception ex)
would catch the resulting thread-abort exception, but wouldn't stop it from propagating up the call chain. It would be better, of course, if there were some way a more meaningfully-named exception could behave likewise, but I know of no such feature in .NET.
– supercat
Dec 6 '13 at 23:24
add a comment |
I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
add a comment |
Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
add a comment |
I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
add a comment |
There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
- The top of all threads (By default, exceptions will vanish without a trace!)
- Inside a main processing loop that you expect to never exit
- Inside a Loop processing a list of objects where one failure shouldn't stop others
- Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
- If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
add a comment |
For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}
add a comment |
Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
Nice to see that we have at least two people that does not like to fix errors...
– Tzen
Nov 7 '17 at 10:18
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%2f21938%2fis-it-really-that-bad-to-catch-a-general-exception%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
14 Answers
14
active
oldest
votes
14 Answers
14
active
oldest
votes
active
oldest
votes
active
oldest
votes
Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
7
Catching all exceptions at language borders to translate them is also good practice.
– Alexandre C.
Aug 3 '11 at 16:12
"The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" " The funny thing is, the .NET framework actually catchesOutOfMemoryException
sometimes.
– jrh
Jun 11 at 17:29
add a comment |
Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
7
Catching all exceptions at language borders to translate them is also good practice.
– Alexandre C.
Aug 3 '11 at 16:12
"The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" " The funny thing is, the .NET framework actually catchesOutOfMemoryException
sometimes.
– jrh
Jun 11 at 17:29
add a comment |
Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
edited Oct 27 '11 at 18:44
Matthew Flaschen
218k37439500
218k37439500
answered Aug 22 '08 at 8:53
John
8,94374952
8,94374952
7
Catching all exceptions at language borders to translate them is also good practice.
– Alexandre C.
Aug 3 '11 at 16:12
"The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" " The funny thing is, the .NET framework actually catchesOutOfMemoryException
sometimes.
– jrh
Jun 11 at 17:29
add a comment |
7
Catching all exceptions at language borders to translate them is also good practice.
– Alexandre C.
Aug 3 '11 at 16:12
"The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" " The funny thing is, the .NET framework actually catchesOutOfMemoryException
sometimes.
– jrh
Jun 11 at 17:29
7
7
Catching all exceptions at language borders to translate them is also good practice.
– Alexandre C.
Aug 3 '11 at 16:12
Catching all exceptions at language borders to translate them is also good practice.
– Alexandre C.
Aug 3 '11 at 16:12
"The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" " The funny thing is, the .NET framework actually catches
OutOfMemoryException
sometimes.– jrh
Jun 11 at 17:29
"The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" " The funny thing is, the .NET framework actually catches
OutOfMemoryException
sometimes.– jrh
Jun 11 at 17:29
add a comment |
Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
add a comment |
Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
add a comment |
Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
answered Aug 22 '08 at 8:50
JamesSugrue
11.2k85491
11.2k85491
add a comment |
add a comment |
Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
1
The catch could be used to add additional information and then rethrow, right?
– Maarten Bodewes
Sep 7 '16 at 14:50
add a comment |
Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
1
The catch could be used to add additional information and then rethrow, right?
– Maarten Bodewes
Sep 7 '16 at 14:50
add a comment |
Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
answered Aug 22 '08 at 8:59
Cheekysoft
26.2k176182
26.2k176182
1
The catch could be used to add additional information and then rethrow, right?
– Maarten Bodewes
Sep 7 '16 at 14:50
add a comment |
1
The catch could be used to add additional information and then rethrow, right?
– Maarten Bodewes
Sep 7 '16 at 14:50
1
1
The catch could be used to add additional information and then rethrow, right?
– Maarten Bodewes
Sep 7 '16 at 14:50
The catch could be used to add additional information and then rethrow, right?
– Maarten Bodewes
Sep 7 '16 at 14:50
add a comment |
In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
add a comment |
In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
add a comment |
In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
answered Aug 22 '08 at 9:02
Erik van Brakel
16.7k24564
16.7k24564
add a comment |
add a comment |
There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
7
Letting an exception bubble up does not mean showing it to the end user. You can (and should) show a generic error page, log it for investigation, and then fix the problem that caused the exception in the first place.
– jammycakes
Apr 20 '09 at 8:52
2
Does not answer question asked.
– Kenneth K.
Feb 12 '16 at 13:47
add a comment |
There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
7
Letting an exception bubble up does not mean showing it to the end user. You can (and should) show a generic error page, log it for investigation, and then fix the problem that caused the exception in the first place.
– jammycakes
Apr 20 '09 at 8:52
2
Does not answer question asked.
– Kenneth K.
Feb 12 '16 at 13:47
add a comment |
There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
answered Aug 22 '08 at 12:47
Tundey
2,53211724
2,53211724
7
Letting an exception bubble up does not mean showing it to the end user. You can (and should) show a generic error page, log it for investigation, and then fix the problem that caused the exception in the first place.
– jammycakes
Apr 20 '09 at 8:52
2
Does not answer question asked.
– Kenneth K.
Feb 12 '16 at 13:47
add a comment |
7
Letting an exception bubble up does not mean showing it to the end user. You can (and should) show a generic error page, log it for investigation, and then fix the problem that caused the exception in the first place.
– jammycakes
Apr 20 '09 at 8:52
2
Does not answer question asked.
– Kenneth K.
Feb 12 '16 at 13:47
7
7
Letting an exception bubble up does not mean showing it to the end user. You can (and should) show a generic error page, log it for investigation, and then fix the problem that caused the exception in the first place.
– jammycakes
Apr 20 '09 at 8:52
Letting an exception bubble up does not mean showing it to the end user. You can (and should) show a generic error page, log it for investigation, and then fix the problem that caused the exception in the first place.
– jammycakes
Apr 20 '09 at 8:52
2
2
Does not answer question asked.
– Kenneth K.
Feb 12 '16 at 13:47
Does not answer question asked.
– Kenneth K.
Feb 12 '16 at 13:47
add a comment |
Well, I don't seen any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
You will catch both IOException and NullPointerException with a generic Exception, but the way you program should react is probably different.
add a comment |
Well, I don't seen any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
You will catch both IOException and NullPointerException with a generic Exception, but the way you program should react is probably different.
add a comment |
Well, I don't seen any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
You will catch both IOException and NullPointerException with a generic Exception, but the way you program should react is probably different.
Well, I don't seen any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
You will catch both IOException and NullPointerException with a generic Exception, but the way you program should react is probably different.
answered Aug 22 '08 at 8:44
Philippe
3,15433150
3,15433150
add a comment |
add a comment |
The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
It is bad to code logic by exceptions, if you expect that file provided by user could not exist, there is a method to check that: File.exists().
– Krzysztof Cichocki
Jun 27 '16 at 11:02
@KrzysztofCichocki - I know this is old, but actually, coding file logic using exceptions in this way is more correct. There's a great explanation by Eric Lippert here. He terms this type "exogenous" exceptions.
– Olly
Jul 4 '17 at 15:35
add a comment |
The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
It is bad to code logic by exceptions, if you expect that file provided by user could not exist, there is a method to check that: File.exists().
– Krzysztof Cichocki
Jun 27 '16 at 11:02
@KrzysztofCichocki - I know this is old, but actually, coding file logic using exceptions in this way is more correct. There's a great explanation by Eric Lippert here. He terms this type "exogenous" exceptions.
– Olly
Jul 4 '17 at 15:35
add a comment |
The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
answered Aug 22 '08 at 8:52
samjudson
47.4k64862
47.4k64862
It is bad to code logic by exceptions, if you expect that file provided by user could not exist, there is a method to check that: File.exists().
– Krzysztof Cichocki
Jun 27 '16 at 11:02
@KrzysztofCichocki - I know this is old, but actually, coding file logic using exceptions in this way is more correct. There's a great explanation by Eric Lippert here. He terms this type "exogenous" exceptions.
– Olly
Jul 4 '17 at 15:35
add a comment |
It is bad to code logic by exceptions, if you expect that file provided by user could not exist, there is a method to check that: File.exists().
– Krzysztof Cichocki
Jun 27 '16 at 11:02
@KrzysztofCichocki - I know this is old, but actually, coding file logic using exceptions in this way is more correct. There's a great explanation by Eric Lippert here. He terms this type "exogenous" exceptions.
– Olly
Jul 4 '17 at 15:35
It is bad to code logic by exceptions, if you expect that file provided by user could not exist, there is a method to check that: File.exists().
– Krzysztof Cichocki
Jun 27 '16 at 11:02
It is bad to code logic by exceptions, if you expect that file provided by user could not exist, there is a method to check that: File.exists().
– Krzysztof Cichocki
Jun 27 '16 at 11:02
@KrzysztofCichocki - I know this is old, but actually, coding file logic using exceptions in this way is more correct. There's a great explanation by Eric Lippert here. He terms this type "exogenous" exceptions.
– Olly
Jul 4 '17 at 15:35
@KrzysztofCichocki - I know this is old, but actually, coding file logic using exceptions in this way is more correct. There's a great explanation by Eric Lippert here. He terms this type "exogenous" exceptions.
– Olly
Jul 4 '17 at 15:35
add a comment |
The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
What would happen if the code which calledCriticalException
also calledThread.Abort(Thread.CurrentThread)
? Because the thread being aborted would be in a known state (callingAbort
), the normal hazards of that method wouldn't apply; code which does acatch(Exception ex)
would catch the resulting thread-abort exception, but wouldn't stop it from propagating up the call chain. It would be better, of course, if there were some way a more meaningfully-named exception could behave likewise, but I know of no such feature in .NET.
– supercat
Dec 6 '13 at 23:24
add a comment |
The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
What would happen if the code which calledCriticalException
also calledThread.Abort(Thread.CurrentThread)
? Because the thread being aborted would be in a known state (callingAbort
), the normal hazards of that method wouldn't apply; code which does acatch(Exception ex)
would catch the resulting thread-abort exception, but wouldn't stop it from propagating up the call chain. It would be better, of course, if there were some way a more meaningfully-named exception could behave likewise, but I know of no such feature in .NET.
– supercat
Dec 6 '13 at 23:24
add a comment |
The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
answered Aug 22 '08 at 9:50
jammycakes
4,21013347
4,21013347
What would happen if the code which calledCriticalException
also calledThread.Abort(Thread.CurrentThread)
? Because the thread being aborted would be in a known state (callingAbort
), the normal hazards of that method wouldn't apply; code which does acatch(Exception ex)
would catch the resulting thread-abort exception, but wouldn't stop it from propagating up the call chain. It would be better, of course, if there were some way a more meaningfully-named exception could behave likewise, but I know of no such feature in .NET.
– supercat
Dec 6 '13 at 23:24
add a comment |
What would happen if the code which calledCriticalException
also calledThread.Abort(Thread.CurrentThread)
? Because the thread being aborted would be in a known state (callingAbort
), the normal hazards of that method wouldn't apply; code which does acatch(Exception ex)
would catch the resulting thread-abort exception, but wouldn't stop it from propagating up the call chain. It would be better, of course, if there were some way a more meaningfully-named exception could behave likewise, but I know of no such feature in .NET.
– supercat
Dec 6 '13 at 23:24
What would happen if the code which called
CriticalException
also called Thread.Abort(Thread.CurrentThread)
? Because the thread being aborted would be in a known state (calling Abort
), the normal hazards of that method wouldn't apply; code which does a catch(Exception ex)
would catch the resulting thread-abort exception, but wouldn't stop it from propagating up the call chain. It would be better, of course, if there were some way a more meaningfully-named exception could behave likewise, but I know of no such feature in .NET.– supercat
Dec 6 '13 at 23:24
What would happen if the code which called
CriticalException
also called Thread.Abort(Thread.CurrentThread)
? Because the thread being aborted would be in a known state (calling Abort
), the normal hazards of that method wouldn't apply; code which does a catch(Exception ex)
would catch the resulting thread-abort exception, but wouldn't stop it from propagating up the call chain. It would be better, of course, if there were some way a more meaningfully-named exception could behave likewise, but I know of no such feature in .NET.– supercat
Dec 6 '13 at 23:24
add a comment |
I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
add a comment |
I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
add a comment |
I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
answered Jan 26 '15 at 18:59
slashdottir
4,37543148
4,37543148
add a comment |
add a comment |
Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
add a comment |
Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
add a comment |
Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
answered Aug 22 '08 at 8:49
jfs
15.4k125484
15.4k125484
add a comment |
add a comment |
I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
add a comment |
I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
add a comment |
I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
answered Aug 22 '08 at 8:45
Matt Hamilton
162k54355305
162k54355305
add a comment |
add a comment |
There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
- The top of all threads (By default, exceptions will vanish without a trace!)
- Inside a main processing loop that you expect to never exit
- Inside a Loop processing a list of objects where one failure shouldn't stop others
- Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
- If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
add a comment |
There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
- The top of all threads (By default, exceptions will vanish without a trace!)
- Inside a main processing loop that you expect to never exit
- Inside a Loop processing a list of objects where one failure shouldn't stop others
- Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
- If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
add a comment |
There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
- The top of all threads (By default, exceptions will vanish without a trace!)
- Inside a main processing loop that you expect to never exit
- Inside a Loop processing a list of objects where one failure shouldn't stop others
- Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
- If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
- The top of all threads (By default, exceptions will vanish without a trace!)
- Inside a main processing loop that you expect to never exit
- Inside a Loop processing a list of objects where one failure shouldn't stop others
- Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
- If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
answered Feb 8 at 21:33
Bill K
53k1385137
53k1385137
add a comment |
add a comment |
For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}
add a comment |
For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}
add a comment |
For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}
For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}
answered Nov 15 at 22:46
Peter Griffin
301312
301312
add a comment |
add a comment |
Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
Nice to see that we have at least two people that does not like to fix errors...
– Tzen
Nov 7 '17 at 10:18
add a comment |
Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
Nice to see that we have at least two people that does not like to fix errors...
– Tzen
Nov 7 '17 at 10:18
add a comment |
Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
answered Jun 4 '14 at 8:21
Tzen
86279
86279
Nice to see that we have at least two people that does not like to fix errors...
– Tzen
Nov 7 '17 at 10:18
add a comment |
Nice to see that we have at least two people that does not like to fix errors...
– Tzen
Nov 7 '17 at 10:18
Nice to see that we have at least two people that does not like to fix errors...
– Tzen
Nov 7 '17 at 10:18
Nice to see that we have at least two people that does not like to fix errors...
– Tzen
Nov 7 '17 at 10:18
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%2f21938%2fis-it-really-that-bad-to-catch-a-general-exception%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
If input is not predictable, and failure is not an option - it's the only way. Of course, there is no good reason not to LOG the error so that it can be properly handled the next time.
– mehtunguh
Dec 2 '12 at 1:59
1
Is this a question that would be better suited to programmers.stackexchange?
– HardcoreBro
Nov 22 '13 at 16:13
I love that this is also called "Pokémon catch — gotta catch 'em all".
– Uwe Keim
Aug 16 '16 at 6:54
Duplicate on SE.SE: Is catching general exceptions really a bad thing?
– jrh
Jun 11 at 17:31