Home  >  Article  >  Backend Development  >  What is the finally statement in C#?

What is the finally statement in C#?

WBOY
WBOYforward
2023-08-30 15:57:02595browse

C# 中的finally 语句是什么?

The final block is used to execute a given set of statements regardless of whether an exception is thrown. For example, if a file is opened, the file must be closed regardless of whether an exception is thrown.

The error handling block is implemented using the try, catch and finally keywords.

Example

You can try running the following code to implement the finally statement -

using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;

      DivNumbers() {
         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) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

The above is the detailed content of What is the finally statement in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete