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.
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!