C# finally
An error may be caused due to exception which ends the method that is running currently in programming, and that method would have opened a file or a network which needs to be closed with ending of the current method. In order to overcome such problems, we have a special reserved keyword in C# called Finally and this Finally block of code will be executed when the execution of try and catch block stops, regardless of what ever conditions causes the stop of execution and it does not matter if the execution of try block stops normally or stopes due to an exception.The Finally block of code is executed and releasing the resources that was engaged is the main aim of Finally block of code and it is written after try and catch block of code.
Syntax:
try { //Block of code } // this can be optional catch { //Block of code } finally { //Block of code }
Working of finally Keyword in C#
- Any resources allocated in the try block can be cleaned up by using Finally block of code and the Finally block of code runs regardless of the exception raised in the try block.
- The statements in the Finally block of code are executed when the control leaves the try block of code. The control is transferred as part of normal execution or execution of goto statement, break statement, continue statement or return statement.
- If there is exception handling, the finally block of code associated with it runs for sure and if there is no handling of exception, the running of finally block of code depends on the triggering of exception unwind operation which in turn depends on the set up of the computer.
- There cannot be more than one Finally block of code in the same program in C#.
- The control will not leave the finally block because there is no goto statement, break statement, continue statement or return statement in finally block.
Examples to Implement C# finally
Below are the examples of C# Finally:
Example #1
C# program to demonstrate the use of Finally block of code in a program.
Code:
using System; //a class called program is defined class program { // a method called ClassA() is defined static void ClassA() { try { Console.WriteLine("We are inside class A"); //An exception is thrown throw new Exception("An exception is thrown"); } //finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("This is the finally block of Class A"); } } // a method called ClassB() is defined static void ClassB() { try { Console.WriteLine("We are Inside class B"); return; } //finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("This is the finally block of class B"); } } // Main Method is called public static void Main(String[] args) { try { ClassA(); } catch (Exception) { Console.WriteLine("The exception that is thrown is caught"); } ClassB(); } }
Output:
Explanation: In the above program, the program is the class defined. Then a method called ClassA is defined in which try and finally blocks of code are written. The try block throws an exception which is caught later. Then Finally block is executed regardless of whether the exception is handled or not. Then a method called ClassB is defined. Then the finally block is executed regardless of whether the exception is handled or not. Then the main method is called.
Example #2
C# program to demonstrate the use of finally keyword in a program that has exception handling.
Code:
using System; //a class called program is defined public class program { // Main Method is called static public void Main() { // two integer variables are defined to store two integers intnum = 10; int div = 0; //try and catch block is defined in which an exception is raised by try block and is handled by catch block try { int op = num / div; } catch (DivideByZeroException) { Console.WriteLine("The divisor can not be zero because it is impossible to divide by 0"); } // finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("We are in the finally block"); } } }
Output:
Explanation: In the above program, a class called program is defined. Then the main Method is called. Then two integer variables are defined to store two integers. Then try and catch block is defined in which an exception is raised by try block and is handled by catch block. Then finally block is executed regardless of the exception is handled or not.
Example #3
C# program to demonstrate the use of finally keyword in a program that has no exception handling.
Code:
using System; //a class called program is defined public class program { // Main Method is called static public void Main() { // two integer variables are defined to store two integers intnum = 10; int div = 0; //try and catch block is defined in which an exception is raised by try block and is handled by catch block try { int op = num / div; } // finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("We are in the finally block"); } } }
Output:
Explanation: In the above program, a class called program is defined. Then the main Method is called. Then two integer variables are defined to store two integers. Then try block is defined.Then finally block is executed regardless of the exception is handled or not. The output of the program is shown in the snapshot above.
Advantages
- Finally, the block of code is executed regardless of what happens within the try block like an exception is thrown or not thrown, if there is a return statement, nothing matters.
- The primary use of finally block of code is to release all the allocated expensive resources in the try block.
- Finally, block ensures that an operation will be performed regardless of any exceptions thrown.
Conclusion: In this tutorial, we understand the concept of finally keyword in C# through definition, syntax, working through programming examples, and their outputs.
Recommended Article
This is a guide to C# Finally. Here we discuss the Introduction to C# finally and its advantages along with its examples and Code Implementation. You can also go through our other suggested articles to learn more –
- What is Random Number Generator in C#?
- Static Constructor in Java | Working | Applications
- TextWriter in C# | Examples
- How to Work Static Constructor in C#?
The above is the detailed content of C# finally. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages such as Python. Be careful when modifying and back up the original files.
