Try/Catch Opinions
-
Actually, in this particular case, there is - the IL is slightly different internally, and it saves clock cycles on the test in CreateDirectory. That's the reason it's in. The important part is actually the second part - hence the point of the example.
Forgive your enemies - it messes with their heads
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility
Ah. I never looked at the IL, I was assuming they were smart enough to make the test inside
CreateDirectory()
as efficient as the one insideExists()
. :doh:Luc Pattyn [My Articles] Nil Volentibus Arduum
-
Ah. I never looked at the IL, I was assuming they were smart enough to make the test inside
CreateDirectory()
as efficient as the one insideExists()
. :doh:Luc Pattyn [My Articles] Nil Volentibus Arduum
Why do I feel the need to go "Helloooooo. Microsoft."?
Forgive your enemies - it messes with their heads
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility
-
Why do I feel the need to go "Helloooooo. Microsoft."?
Forgive your enemies - it messes with their heads
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility
I don't know. Besides, I prefer How questions over Why questions any day. :)
Luc Pattyn [My Articles] Nil Volentibus Arduum
-
Indeed, where it's appropriate, a simple check can often save time. Ultimately, as you progress, you end up building a handy set of utility methods that you can use, for instance here's a simplified version of a file create that you could use:
public static FileStream TryCreateFile(string fileToCreate)
{
string directoryName = Path.GetDirectoryName(fileToCreate);
if (!Directory.Exists(directoryName))
Directory.CreateDirectory(directoryName);
return File.Create(fileToCreate);
}Forgive your enemies - it messes with their heads
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility
Pete, this is good solid code (I'd expect no less from you), but in a way I can see this as a bit of a diversion from the original topic: error handling and Try/Catch. In your code, yes, a Directory will be created, if none exists, but, what about the case it's an error ... for this particular application ... if the user is trying to save a file to a Directory that does not exist ? And, what about the case where the Directory exists, but is read-only ? Should code like this be "throwing" errors ? And what, if the code "throws," should be "catching them." And, as Abbott said to Costello: "Who's on first ?" best, Bill
"... Sturgeon's revelation. It came to him that Science Fiction is indeed ninety-percent crud, but that also—Eureka!—ninety-percent of everything is crud. All things—cars, books, cheeses, hairstyles, people and pins are, to the expert and discerning eye, crud, except for the acceptable tithe which we each happen to like." early 1950's quote from Venture Sci-Fi Magazine on the origin of Sturgeon's Law, by author Theodore Sturgeon: source Oxford English Dictionary on-line "Word-of-the-Day."
-
I have several small programs that scrap input and load it into a database. Since much of the code relies on external resources being ready, a lot of my code ends up being in try/catch blocks. Is there a lot of overhead associated with these? I have tried to consolidate interaction with external sites and db's so there are a minimal number. Is there a better way to do this than having a block in each method? Thx Mark Jackson
mjackson11 wrote:
Is there a lot of overhead associated with these?
Not unless there are in fact a lot of exceptions.
mjackson11 wrote:
Is there a better way to do this than having a block in each method?
That depends on what the application does and what you do in the block. If you have a server that runs 24x7 and moves data from one remote source to another then sometimes there will be connection failures. In a case like that then the it must catch exceptions that originate from communication problems and continue. If it is a console app that runs either pass/fail by a human and they are not supposed to run it unless everything is already working then catching an exception is optional. Maybe friendly but also an extreme case. If the app needs to handle 3 sequential cases and all must pass then you must handle exceptions so that you can take some sort of action if step 3 fails after the first two succeeded. When I write servers I catch almost everything so I can log it. And so on...
-
mjackson11 wrote:
Is there a better way to do this than having a block in each method?
Yup, you can hook an event that catches all unhandled exceptions[^]. There you can log it, without having the need for a try-catch everywhere. Log everything you encounter, and handle those using try-catch blocks; some will be bugs, some will be exceptions that need a) user interaction (file in use, database dead), b) no user interaction. Handle what you can and log everything.
Bastard Programmer from Hell :suss:
-
That is a last best effort rather than being a general solution because the AppDomain will then exit (or application will exit at the top level.)
-
That's the idea with an unexpected exception; your application is in an unknown state, and hence, should terminate.
Bastard Programmer from Hell :suss:
I don't see anything in your original post that suggested it was only applicable for "...unexpected exception; your application is in an unknown state". Most exceptions will not fall into that category. In general your suggestion is not applicable for exceptions. And nothing I see in the OPs posts suggests it is applicable to the OP.
-
I have several small programs that scrap input and load it into a database. Since much of the code relies on external resources being ready, a lot of my code ends up being in try/catch blocks. Is there a lot of overhead associated with these? I have tried to consolidate interaction with external sites and db's so there are a minimal number. Is there a better way to do this than having a block in each method? Thx Mark Jackson
-
Pete, this is good solid code (I'd expect no less from you), but in a way I can see this as a bit of a diversion from the original topic: error handling and Try/Catch. In your code, yes, a Directory will be created, if none exists, but, what about the case it's an error ... for this particular application ... if the user is trying to save a file to a Directory that does not exist ? And, what about the case where the Directory exists, but is read-only ? Should code like this be "throwing" errors ? And what, if the code "throws," should be "catching them." And, as Abbott said to Costello: "Who's on first ?" best, Bill
"... Sturgeon's revelation. It came to him that Science Fiction is indeed ninety-percent crud, but that also—Eureka!—ninety-percent of everything is crud. All things—cars, books, cheeses, hairstyles, people and pins are, to the expert and discerning eye, crud, except for the acceptable tithe which we each happen to like." early 1950's quote from Venture Sci-Fi Magazine on the origin of Sturgeon's Law, by author Theodore Sturgeon: source Oxford English Dictionary on-line "Word-of-the-Day."
Bill, sorry for the delay in replying. To answer your unspoken question, yes and no - the code was answering the premise that exception handling should not be relied upon when a simple check can solve the issue. So, what is the error we're coping with in this example? It's the fact that you can't write a file into a directory until that directory exists. The other side here, is the fact as you've rightly pointed out, that this doesn't address all the cases that can be tested for. In my defence, I wrote this as a cut-down sample in the CP editor as an example only, but you are right, there are many other conditions that could be catered for. The point is really two-fold, if you create a utility API to handle the conditions that you can test for (rather than catch as an exception) then you have given yourself a real advantage when you come to write your production code. No, you won't get rid of exception handling altogether, but you won't be relying on it to cope with conditions that could easily have been tested for. So, why do I advocate this? Well, exception handling is meant to indicate something that you couldn't reasonably predict and cope with. The mark of a good application is one that doesn't surprise users, so I'm either going to have to do lots of try/catch (and then cope with the failure before triggering the condition in the try/catch again), or I can put something in place to cope with the error before it occurs and make an intelligent decision about coping with the problem. I hope this somewhat rambling post conveys some of what I was trying to get across.
Forgive your enemies - it messes with their heads
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility