Answered by:
Why specific exceptions?

Question
-
I always see people recommend to never catch a general exception but always catch specific ones.
But I don't understand why. Usually the exception text (not message, the whole text including call stack) is the same for a general exception and specific exceptions, at least the exceptions where I made a comparison.
So why would I risk letting an unanticipated exception crash the application?
If the method fails due to an exception, usually it's not something I can handle at that point anyway but must inform the user about.
And many exceptions can be avoided by simple checks anyway, so if for example I want to parse an int from a string and the string contains letters I can just use TryParse and don't do anything or tell the user that parsing failed.
Either way I am programming for 4 years now and cannot think of a situation where just catching a certain type of exception would let me handle a situation a normal variable check like TryParse of 'if code > 0' would not be better.
Could you explain to me what exactly the advantage of catching various specific exceptions before catching a general exception is good for?
Thanks.
- Moved by Michael Sun [MSFT]Microsoft employee Wednesday, December 19, 2012 5:34 AM Forum Restructure (From:Visual C# Language)
Answers
-
You should specific exceptions so you and messagebox a more user-friendly reason as to why the program failed. What i generally do is crash the program purposly so i understand the exception and catch each individual exception with a different messagebox explaining what happend. and after i catch all specific exceptions i can think of catch a general just to be sure i didnt forget anything.
Devon Quick
- Proposed as answer by Jason Dot Wang Tuesday, December 18, 2012 6:54 AM
- Marked as answer by Jason Dot Wang Monday, December 24, 2012 9:19 AM
All replies
-
it's just that specific catches is better. When you're specific, it means that you actually understand, more concretely, what your application is doing, and have more control over it. In general, if you come upon a situation where you just catch an Exception, log it and continue, there's probably some bad things that are going on anyway. If you're specifically catching the exceptions that you know a code block or method can throw, then there's a higher likelihood you can actually recover instead of just logging and hoping for the best.
Catching general exception leaves your program in an undefined state. You don't know where stuff went wrong so you don't know what your program has actually done or hasn't done.
Handle specific exceptions and then last with generic exception if you think application will crash because of some exceptions generated with an application which cannot be dedicated by developer
Refer this site http://msdn.microsoft.com/en-us/library/ms182137%28v=vs.80%29.aspx
why we should not use general exception types -
I still don't really see a reason.
How WOULD I actually recover from a say, FileNotFoundException?Create the file? Obviously not, so all I can do is either tell the user I could not find the file or just swallow it and don't do anything, not annoying the user with more or less obvious error messages (depends on the situation if you want to tell or swallow).
Nothing I could not do better with an appropriate check like File.Exists() in this case.
And usually it's not the entire application that is in an undefined state but only the current method.
Usually if something like reading information from a file fails I either ignore it if it's secondary or tell the user that the whole operation failed because the file could not be read.
Only if I manipulate global resources like files or the db or maybe some application config the entire application could be in an undefined state.
But in such cases, I would rather be safe and return to the state before executing this method regardless of the type of exception that occurred.
I cannot really think of an exception that would really have to shut down the entire application (remember, the user will have to do all input all over again in this case, even if the user cannot save files, it is possible to simply copy text and paste it into editor if the application does not crash but only shows an error message).
Only in the main method of program perhaps.
What I am really missing is a solid example o a situation where simple checks to prevent anticipated problems cannot do better what catching specific exceptions does.
Anonymous: “If my program has a feature to auto-save unsaved work every 10 minutes, and the auto-save procedure (which may use a third-party library) throws an unchecked exception, are you suggesting that the program should simply crash out, because this exception must not be handled?”
Usability and functionality should be top priority for application design, NOT catering to established coding standards.
Personally I would instantly demand a refund for an application that crashes during autosave.
-
Suppose you had code to read a file, and return the number of lines within the file. This concievably could cause two distinct errors. 1) the file does not exist, 2) the file exists but permission to open it is lacking. Having a general catch would only partially solve the problem. Trapping for the two error types can help the user, or the developer, understand why the issue occured. It is always better to give specific info, or to handle the specific problem if possible. Above, the former issue (file non-existant) may be solved by a file browser dialog. File permission might be solved by telling the user to run as admin.
--
Mike -
It might be you don't see reason, because you don't have one.
Checks all those things that usually prevent from crashes like the File.Exists usually works, but that's not something that you can rely on in every case. Operations, usually environmental operations, like file system, are good examples where you can not be sure, not even after several checks, that condition will be required on next line.
And you make point with application that always has user to make correction if required when in reality more and more applications, and most complex ones, are automatic or semi-automatic where user interaction is not even required (or is very minimum) to applications or system of applications to perform. In those systems it's lot of easier build error recovery with detailed error data than general exception where you need then to figure out what went wrong and how to recover without that user who might know more than application does.
-
Hmm. This is based on the predicate that always 'people recommend never to catch a general exception but always catch specific ones'.
I don't think I've seen that recommended. What I have seen is 'catch specific exceptions before catching general ones' i.e. if you catch specific exceptions then the last catch block should catch general exceptions. If the action can result in a few specific exceptions and you can deal with each one (that makes the general one unnecessary), or you decide not to handle other exceptions and so allow them to bubble up the stack.
That said, you are perfectly right to favour error checking over exception handling. Exception handling really ought to be for exceptions that you can do nothing about except gracefully die e.g. net work failures. Non-existent files can be checked for and appropriate action taken, but some would argue that between the check and the use the file could disappear. Of course that's possible but, I suspect, highly unlikely for local files. There is also the problem that somethings can only be handled using exceptions e.g. not having the right permissions when trying to access a directory. You cannot make an error check before hand so you have to handle the exception and use it to control program flow. In this case catching the specific access violation error can allow the program to continue, while any other exception might be considered fatal.
The attitude some people have, that you should protect against all possible exceptions (anticipated or not), means that you could go to the extreme of wrapping almost every line in a try...catch block. I prefer proper error handling and keep exception handling to a minimum. :)
Regards David R
---------------------------------------------------------------
The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
Every program eventually becomes rococo, and then rubble. - Alan Perlis
The only valid measurement of code quality: WTFs/minute. -
You should specific exceptions so you and messagebox a more user-friendly reason as to why the program failed. What i generally do is crash the program purposly so i understand the exception and catch each individual exception with a different messagebox explaining what happend. and after i catch all specific exceptions i can think of catch a general just to be sure i didnt forget anything.
Devon Quick
- Proposed as answer by Jason Dot Wang Tuesday, December 18, 2012 6:54 AM
- Marked as answer by Jason Dot Wang Monday, December 24, 2012 9:19 AM
-
I see. Thanks for the feedback.
It's just that every article or post I've come across on this matter so far condemned general exceptions and glorified specific one, as if simply catching specific instead of general exceptions would automatically make your program better.
Indeed, catching specific exceptions for detail in error messages is better for the user.
I'll keep that in mind...next I get a chance to use proper exception handling. At the moment I'm working for a company where exception handling is well, not a priority to put it mildy...