Try without catch

As a note on what William is saying - if you expect an exception could happen - deal with the problem before it happens.

Doing a File.Exists check is extremely fast - having an exception throw and the stack unwind is INCREDIBLY slow. We’re talking a difference of microseconds in comparison to miliseconds. Exceptions should be avoided wherever possible.

The stream write example in the first post is a very good example of a good implementation of try/catch, except it should be handling the error in some way. A write is something that can have numerous things beyond your control go wrong (cable falls out, io errors due to bad disks, disk full, signal noise between your device and the remote device, etc).

Exceptions are there for when the unexpected happens, not for something you can expect.

Keeping in mind this was for non-critical logging for my autonomous vehicle that would not be tethered; and any appreciable delays of trying to re-mount the SD, reopen the file, etc would delay sensor and motor operations:

What would you suggest the catch do in this case?

The exceptions in that case could be, disk full, some wierd mem full, some driver issue or mechanical hickup. In those cases, not sure you can do much at the time except stop logging if it was imperitive you did not shutdown to get back home until you can debug the issue. You could save the critical error in memory and figure out way to read from memory (i.e. serial, usb, network, wireless, egyptian carrier pigeons, etc).

Bingo - this is why I just put the catch {}.

If I had a wired/wireless network, then I would send info that way. If I was tethered via USB, I would have done a Debug.Print().

Developing code to allow for every possible failure will lead to writing 90% error handling, and 10% actual logic, or worse. Providing a graceful exit for every possible cause will likely to blow up your program beyond the limits of a FEZ.

On a normal computer you can get away with this by putting up a message box saying ‘fatal error near line 1’, but on an embedded system this gets tricky. You wont want your fez to be deadlocked.

I think the best way to tackle this is to put a try/catch on a very high level of your application to avoid the problems that ‘on-resume-next’ will bring. I am thinking ‘auto-reset’ here.

The only real advice I can give is not to do a try/catch(/finally) in a tight loop or deep inside a driver. It’ll kill performance. Put the ‘try’ around the loop.

For your example of non-critcal logging, you could have a flag on your logging class. If an error comes up and is caught while writing, and occurs on the next… lets say 3… writes, then stop writing data. Do you really want 3-5% of your processor time being taken up with stack unwinds? (assuming around 5 exceptions a second… ie: a 5hz log rate).

As far as catering for every eventuality - sure that is pointless. You must however check for the most basic and common ones its only an extra 10-15 bytes of IL to check if something is there!

When you’re possibly dealing with users, a simple check to see if the sd card is there to be mounted, the folder is there, the file exists and can be written to the first time you go to write, nothing too difficult.

I agree with RobV : I think try/catch should be located only in high-level functions.

I think a program should be designed to never throw any exception. I try to explain:

In lower-level functions (in data layer or business layer), like in your example writing in a stream, you should check the most obvious preconditions to prevent any exception (For example, checking the file exists, or checking if there is enough memory, or …). If you do so you don’t need a try/catch at this location.

But it is impossible to prevent all exceptions (there are hundreds of reasons why a fileStream.Write may throw an exception), that’s why you need to find a dozen of higher-level functions where to put a try/catch. Those high-level functions should “cover” all your program to prevent an exception to move up to you main loop().

If when your program runs an exception is thrown, then you have to consider this as a bug, and put a new precondition check in the funtion that thrown the exception… And over and over…

But I can tell you : there is no perfect answer! There has been hours or even days of discussions about exception handling at my work with other C# developers. And even after this we don’t have found the perfect solution!

You may also catch one or two important exceptions and “ignore” the others by using a second empty catch block.

try
{
...Code...
}
catch (EWhateverExceptionYouLike ex)
{
.. deal with this specific exception ...
}
catch (EThisOneToo ex)
{
.. deal with this one too ...
}
catch (Exception ex)
{} // "Ignore" others

This way, your code won’t bug/halt with an unhandled exception, while you still handle the most important ones (for your particular case).

I think a better way is to catch the specifics (knowns, or expected) exceptions, and let the unknowns be handled on a higher level.

I also should mention that multiple catch statement will need to be ordered somewhat. If, for example, you do this:


try
{
}
catch(Exception ee)
{
}
catch(WhatEverOtherException)
{
}


the ‘whateverbit’ will never gets executed because the superclass (Exception) will be handled first and only - only one of the catch blocks will be executed.