Properly handling Exceptions with System.ApplicationException and C#

Handling of exceptions is very important and usually not very well understood by many developers. Exceptions occur all the time. The most often times this happens then hardware failure occur and program cannot runt to the end. In this case catching exception, and responding to the event is critical. We don’t want users to be left in the dark. We can catch exceptions by using try/catch combination. Any code that is prone to possible issues can be enclosed within try brackets and then in catch we handle Exception in a more friendly way. We can analyze it, log it and etc… We can also define our own exceptions from System.ApplicationException class. If we have more then one exception only one will be presented to the user at a time. So rule of thumb is to use the most specific exception first and then less specific so that user can deal with the most understandable issues and resolve it. Exception handling is a nice feature but it comes with the price of degraded performance. One more thing to remember is that we should declare simple variable outside of try block so that we can handle disposal of these variable in the final block

            StreamReader str = new StreamReader("file.txt");
            try
            {
                Console.WriteLine(sr.ReadToEnd());
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error reading file: " + ex.Message);
            }
            finally
            {
                sr.Close();
            }