Try-Catch-Finally in c#

Exceptions allow an application to transfer control from one part of the code to another. When an exception is thrown, the current flow of the code is interrupted and handed back to a parent try-catch block. C# exception handling is done with the following keywords: try, catch, finally, and throw

Syntax



try
        {
            //statements that may raise exceptions
        }
        catch
        {
            //Catch the exception
        }
        finally
        {
            //This block of code will always get executed whether an exception occurs or not as long                as there are no exceptions within this block itself.
        }




Example 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class ExceptionHandlingExampleProgram
    {
        static void Main(string[] args)
        {
            object o2 = null;
            try
            {
                int i2 = (int)o2;   // Error 
            }
            catch (Exception exceptionObj)
            {
                // log exception from exceptionObj
            }
            finally
            {

                // do cleanup work here
            }

        }
    }
}