Home »
.Net »
C# Programs
C# program to demonstrate InvalidCastException exception
Here, we are going to learn about the InvalidCastException exception and demonstrating the example of InvalidCastException exception in C#.
Submitted by Nidhi, on September 16, 2020
Here we demonstrate the exception for invalid typecasting. Here we will un-box an integer number but we use the "short" keyword for typecasting. Then the exception will generate and caught in the catch block.
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.
C# Exception Handling Programs »