PISNA
Dicas para Tratamento de Excepções
About Unhandled Exceptions
The great thing about a good global exception handler is that it makes the rest of your code easier to read. Rather than cluttering up your code with Try..Catch blocks for every possible error condition, no matter how rare, you can simply rely on the solid, built-in global handler to deal with those oddball scenarios-- and to notify you when they happen!
So then the natural question that most developers ask is, "When should I catch exceptions"? And it's a very good question. Here are some guidelines that I have found useful.
- Unless you have a very good reason to catch an exception, DON'T. Exceptions are supposed to be exceptional, just like the dictionary meaning: uncommon, unusual. When in doubt, let the calling routine, or the global exception handler, deal with it. This is the golden rule. The hardest kinds of exceptions to troubleshoot are the ones that don't even exist, because a developer upstream of you decided to consume it.
- If you can correct the problem implied by the exception. For example, if you try to write to a file and it is read-only, try removing the read-only flag from the file. In this case you handled the exception and fixed the problem, so you should eat the exception. It doesn't exist, because you fixed it.
- If you can provide additional information about the exception. For example, if you fail to connect via HTTP to a remote website, you can provide details about why the connection failed: was the DNS invalid? Did it time out? Was the connection closed? Did the site return 401 unauthorized, which implies that credentials are needed? In this case you want to catch the exception, and re-throw it as an inner exception with more information. This is a very good reason to catch an exception, but note that we are still re-throwing it!
- Always try to catch specific exceptions. Avoid catching System.Exception whenever possible; try to catch just the specific errors that are specific to that block of code. Catch System.IO.FileNotFound instead.
There are, of course, times when you'll want to violate these rules for completely legitimate reasons-- but at least consider them before you do.
Comments:
Enviar um comentário