A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

C# program to demonstrate the finally block in exception handling
Q:

C# program to demonstrate the finally block in exception handling

0

C# program to demonstrate the finally block in exception handling

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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()
    {
        try
        {
            ExceptionDemo E = new ExceptionDemo();

            E = null;
            E.PrintHello();
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.WriteLine("Finally block executed");
        }
    }
}

Output:

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

Explanation:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now