Try/Catch Use Convention(s)

2019-05-09 09:27发布

问题:

What is the convention for Try/Catch outside of obviously needed locations(such as getting specific user input)? While code re-use is an important idea behind OOP, is it expected that each (example) array access should have a try/catch? Is it primarily the designer's decision of what can throw an exception, and those parts of the program that should be well regulated enough to never throw an exception?

Ex. An array of playing cards is, and should always be, 52 cards. No try/catch is necessary. Or since an array out of bounds exception could cause a run-time error, and the deck could be used at a later date with jokers added, then put it in now?

回答1:

Your example is a little off.

Assuming you have an array of 52 elements, the correct way of handling this is to test that your index is within the bounds of the array before even attempting to access it. This is far better than simply wrapping the code in a try .. catch in there.

Try Catch is there to help save us from ourselves. If a given method is coded properly then there is very little reason to use them. By properly I mean that you verify your inputs are within the ranges expected and you've tested enough to know that the code won't "except" out. Of course, an example of "very little" include calls to unmanaged resources such as the SqlConnection object.

Point is, it's a crutch that is a last ditch effort to salvage something usable out of that particular code blocks execution.

If, however, there is literally nothing that can be done about the exception then I'd say your only choices are to ignore it and let it bubble up or catch, log and rethrow.



回答2:

You should only catch exceptions, you can actually handle. I.e. you should not have try/catch statements everywhere.

As for throwing exceptions, you should throw an exception when there's no better option. If you can handle user input meaningfully then there's no reason to throw an exception in that case. Without knowing the specifics I would assume that there's no need for an exception in this case.



回答3:

Trey Nash in his book Accelerated C# recommends (as probably most do) to program in a way that negates use of try/catch branches. Most try/catches that you see can be done away with by better programming. There are instances where you need it, mainly in dealing with file handles, database connections, basically anytime you need to use a using statement (which behind the covers is a try/finaly block) with a type that implements IDisposable. Any use of something in the OS that is beyond your control where something could go wrong use a try catch.

And try not to use the general

 try {    //some exception thrown }
 catch (Exception ex) {     }

That's too general, do the best you can to handle the more relevant exceptions that can happen instead of having them all go into a general catch statement.



回答4:

In general i tend to catch exceptions, log them, rethrow and then ultimately have some application level exception handling that presents a general error to the user.

In specific cases where you might know what is causing the exception (e.g. you catch an exception that indicates thatthe connection to the database server is down) you catch the specific exception and then generate an appropriate error message for the user.

If invalid user input is causing exceptions then you have buggy code and you need to validate your input.



回答5:

You should avoid using try/catch as it's very expensive. In most scenarios you can implement necessary check to avoid exceptions being thrown.

With regards to collections or arrays you can check how many items you have in the collection to avoid errors.

The valid place where you would use try catch would be when reading file or accessing 3rd party resource.

When you catch exception, log it and try to find a way of avoiding it.

Also when rethrowing exception use code below try {

    }
    catch (Exception ex)
    {
        throw;
    }

Hope that answers your question.



回答6:

Try/Catch says by itself, that you tried to do something, something happened (in our case no a good thing) and you're trying to catch that exception to do something with that information.

Moral: if you know that there could be an exception, and if you know what you're gonna do in case it happen, use try/catch to develop your exception handling logic.

If not, there is more meaning to have try/finally (for example during IO access for allocated resources disposing logic execution guarantee).

Hope this helps.



回答7:

Just thought I'd throw this into the mix as well. Eric Lippert made an excellent post about this a few years back:

http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx