Questions about C# try, catch, finally

I have never used these before and am wondering, can they be used to make your scripts faster?

For instance this is the way I have always written things in the past, with first a check to see if something exists and then I test its value.

public bool Expired (String name)
{
  if (!myDictionary.ContainsKey (name)) return false;
  return myDictionary[name] < timeMs;
}

It occurred to me that it might be faster to check things once and use try, catch, finally, if it fails.

public bool Expired (String name)
{
  try
  {
    return myDictionary[name] < timeMs;
  }
  catch(KeyDoesNotExistException de)
  {
    return false
  }
  finally
  {
    return false;
  }

}

So my question, is the second method the way it should be done? It certainly makes for ugly looking code. :slight_smile:

No, this is definitely not the way it should be done :slight_smile:

Using exceptions for anything other than exceptional things is generally considered bad practice.

Plus it’s going to be much slower. When an exception is thrown the runtime has to do a bit of jiggery-pokery to prepare for running up the call stack to find the catch block (or crash the program).

I don’t have any specific figures but I would guess that throwing an exception would be an order of magnitude slower than just checking if your dictionary contains the key.

Edit:

Here is something from MSDN

There is no right or wrong way, but there is often a standard way wherever you happen to work, and of course personal preference.

Personally my view is this : try catch systems can be easier for beginners, but in general I tend to avoid avoid them where I can.

Why?

Because they’re over-verbose, tend to obfuscate, are slower to execute, harder to debug once you’re dealing with a true OOPL (nesting is a biotch with try/catch systems) and take control that I find useful away from me. I also find they tend to result in hackier and more difficult to fix code that might easily allow critical run-time errors to pass unnoticed.

Of course a lot of that is like I said personal preference, and others I’m sure have opposite views. Use whichever system you find most productive, the only important thing is to learn to code defensively but sensibly and make solid bug-free code.

The trick is to use try-catch in the right places. The good thing with a try-catch system is, imo, that it’s more safe to use whenever you don’t really know what could possibly go wrong. Atm I’ve never used it in C# but use it frequently in Java (not JS, only Java) and I feel that it gives me a more robust code - if statements tend to be buggy, especially when many things can go wrong/there are many alternatives.

In your case, I would remove finally and just go with try-catch, maybe make it more general and say that “if anything goes wrong, return false”.

So to sum it up, I don’t know if it becomes faster to compile, but imho, it becomes safer.

I disagree with this sorry. Chucking try-catches, expecially ‘catch alls’ around the place is not the way to write good code.

Most of the time you want it to throw the exception, to alert you that something is wrong in your code.

For example, if in the code above, the OP put a Catch-All (i.e. catching Exception) around that code and he forgot to initialise MyDictionary, then he’s not going to know. It will harmlessly return false and you’ll be looking for the bug elsewhere.

There are really only a few places where you need to used exceptions. If you are writing your own, self contained, code you should know what the possible situations are and put checks in so they don’t throw exceptions. Check everything for null, be careful with arrays and casts, etc.

Everytime you get an exception it’s a good thing, because it means you’ve pinpointed exactly where you need to put an extra check in.

The only… um… exception to that is if you are dealing with external components, like networks or file systems or 3rd party libraries. Here things are completely out of your control you need to prepare for things to throw exceptions.

Basically, if you don’t know exactly what the specific exception means and how to recover from it, you shouldn’t be catching it.

Some errors are fatal errors, they should be caught by a high level catch-all that either shuts down or restarts the program. If you catch them randomly throughout your program then you’re going to get weird behaviour that’s difficult to see what’s wrong.

Personally, I don’t return true/false, but messages to tell what’s wrong, and I also specify what kind of exception when I know what could go wrong. Sometimes if-statements doesn’t work properly and suddently the system will crash before you’ve even realized what had happened. But yeah, this doesn’t mean that there should be try-catches all over the place:

But:

I’m not sure if I understand this correctly, do you mean that we should use try/catch in addition to the if-statements? In case something went wrong?

… hence:

To me, dealing with external files without using try-catches is like dealing with hell :frowning: