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 InvalidCastException exception
Q:

C# program to demonstrate InvalidCastException exception

0

C# program to demonstrate InvalidCastException exception 

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 InvalidCastException exception is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# Program to demonstrate "InvalidCastException" Exception

using System;

class ExceptionDemo
{
    static void Main(string[] args)
    {
        int     intNum = 786;
        object  Ob;

        Ob = intNum;
        try
        {
            Console.WriteLine("Un-boxing a integer number");
            int num = (short)Ob;
        }
        catch(InvalidCastException exp)
        {
            Console.WriteLine(exp.Message);
        }
    }
}

Output:

Unboxing a integer number
Specified cast is not valid.
Press any key to continue . . .

Explanation:

In the above program, we created a class ExceptionDemo that contains the Main() method. In the Main() method, we created a variable intNum and object Ob.

Ob = intNum;
try
{
    Console.WriteLine("Un-boxing a integer number");
    int num = (short)Ob;
}
catch(InvalidCastException exp)
{
    Console.WriteLine(exp.Message);
}

In the above code, we type-caste object Ob into integer but we used the short keyword for typecasting then InvalidCastException gets generated that will be caught in the "catch" block and then print the exception message using the "Message" property 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