By David He, Software Engineer

As C# programmers we know that it is good practice to put code into the try-catch block for the application execution security and put any executing-required code in the finally block; but some people forget to use a try-catch block in coding and some people do not fully understand how it works when we have multiple layers of try blocks. This small misunderstanding may create a bug which is difficult to catch in the application. 

1. Why it is good practice to use try-catch block? The following code is a simple C# application. This application will delete the “test” directory in D drive.

It seems that this block code has no problems. You expect to see “I am a good programmer”; but you will see “I am a bad programmer” sometimes. It depends on the files or directory of the “test” directory shared or edited by other people or other applications. If any file or directory in “test” directory shared or edited by other people or other applications is the function System.IO.Directory.Delete(dir, true), the application cannot delete the directory “test”. In this case, it has a running error. One good thing is that this block code uses a try-catch block in the main function and the execution will throw the exception to the catch block, otherwise you will have no idea why “I am a bad programmer”. To fix this issue, we need to add a try-catch block in the function.    

Now you are always a good programmer!

2. Use multiple layers try block.

A catch block must be added to handle running errors. For multiple layers, the try block will throw the error into the first upper catch block if any block does not handle the running error.

We can change the function in the above application.

Now you still see “I am a bad programmer” if you run this application. Since it does not handle the running error of the try block in this function, this error will be handled by the first upper catch block, and any code after the function deleteDir will not be executed. It is good practice to use a catch block to handle any possible running error if you use a try block, otherwise, it will throw the running error to the first upper catch block. Another important keyword in C# is “using”; but it results in little difference. try/catch is used for exception handling while “using” ensures the object is disposed. “using” is a convenient syntax for database operation or in the case that the resource is expensive. This is a topic for another day. With these tips, you too can always be a good programmer.