- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finally keyword in C#
The finally keyword is used as a block 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.
Syntax
Following is the syntax −
try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code } catch( ExceptionName e2 ) { // error handling code } catch( ExceptionName eN ) { // error handling code } finally { // statements to be executed }
Example
Let us see an example to implement the finally block −
using System; public class Demo { int result; Demo() { 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); } } public static void Main(string[] args) { Demo d = new Demo(); d.division(100, 0); } }
Output
This will produce the following output −
Exception caught = System.DivideByZeroException: Attempted to divide by zero. at Demo.division(Int32 num1, Int32 num2) in d:\Windows\Temp
0kebv45.0.cs:line 11 Result = 0
Advertisements