s

C# try catch finally edit button Edit

author
Rakesh Kumar Sutar | calendar 20 January 2021 | 2166

Introduction

C# exception is a response to an exceptional circumstance that arises while a program is running.


try - A try block identifies a block of code for which particular exceptions is activated.
catch - A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally - The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

Example

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

namespace Hello_World
{
    
    class Program
    {
        int result;

        Program()
        {
            result = 0;
        }

        public void division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }
        }
        static void Main(String[] args)
        {
            Program d = new Program();
            d.division(25, 0);
            Console.ReadKey();
        }
    }
}

Output