Q:

C# program to demonstrate InvalidCastException exception

belongs to collection: C# Exception Handling Programs

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)

C# program to demonstrate the multiple catch block... >>
<< C# program to demonstrate DivideByZeroException ex...