SoFunction
Updated on 2025-03-07

Analysis of the usage of try catch finally in C#

This article describes the usage of try catch finally in C#. Share it for your reference. The specific analysis is as follows:

The program block in try is a program block that may cause errors, the program block in catch is a code block that will only be executed when an error occurs, and the program block in finally is a code block that will be executed regardless of whether an error occurs.

Sample program:

Copy the codeThe code is as follows:
using System;
using ;
using ;
using ;
 
namespace Sample_01_CA
{
    public class Complex
    {
        static void Main(string[] args)
        {
            int i = 2008;
            int j = 0;
            try
            {
                int result = i / j;
            }
            catch
            {
("The value of J variable is 0");
            }
            finally
            {
                (());
            }
            ();
        }
    };
}

The program output is:

The value of J variable is 0

0

Sample program:

Copy the codeThe code is as follows:
using System;
using ;
using ;
using ;
 
namespace Sample_01_CA
{
    public class Complex
    {
        static void Main(string[] args)
        {
            int i = 2008;
            int j = 2;
            try
            {
                int result = i / j;
            }
            catch
            {
("The value of J variable is 0");
            }
            finally
            {
                (());
            }
            ();
        }
    };
}

The program output is:

0

I hope this article will be helpful to everyone's C# programming.