C# program to demonstrate the finally block in exception handling

Here, we are going to learn about the finally block in exception handling and demonstrating the example of finally block in exception handling in C#.
Submitted by Nidhi, on September 16, 2020

Here we demonstrate the finally block in exception handling. The finally is always executed in the program either an exception is generated or not.


The source code to demonstrate the finally block in exception handling is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the finally 
//block in exception handling.

using System;

class ExceptionDemo
    void PrintHello()
        Console.WriteLine("Hello World");
    static void Main()
            ExceptionDemo E = new ExceptionDemo();

            E = null;
        catch (NullReferenceException e)
            Console.WriteLine("Finally block executed");


Object reference not set to an instance of an object.
Finally block executed
Press any key to continue . . .


In the above program, we created a class ExceptionDemo that contains two methods PrintHello() and Main(). The PrintHello() message will print "Hello World" on the console screen. 

In the Main() method, we created an object E in the "try" block. Then we assigned the value "null" to the reference E and then call PrintHello() method with a null reference. That's why the NullReferenceException exception gets generated and caught by the "catch"  block that will print the exception message on the console screen and then the "finally" block gets called and print "Finally block executed" message on the console screen.

C# Exception Handling Programs »


What's New (MCQs)

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.