C# Program to Demonstrate Exception Handling for Invalid TypeCasting in UnBoxing
Posted by Superadmin on August 12 2022 07:58:36

C# Program to Demonstrate Exception Handling for Invalid TypeCasting in UnBoxing

 

 

This is a C# Program to illustrate exception handling for invalid typeCasting in unboxing.

Problem Description

This C# Program Illustrates Exception Handling for Invalid TypeCasting in UnBoxing.

Problem Solution

Here it demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

Program/Source Code

Here is source code of the C# Program to Illustrate Exception Handling for Invalid TypeCasting in UnBoxing. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Illustrate Exception Handling for Invalid TypeCasting in UnBoxing
 */
class TestUnboxing
{
    static void Main()
    {
        int num = 123;
        object obj = num; 
        try
        {
            int j = (short)obj; 
            System.Console.WriteLine("Unboxing");
        }
        catch (System.InvalidCastException e)
        {
            System.Console.WriteLine("{0} Error: Incorrect unboxing", e.Message);
        }
        System.Console.Read();
    }
}
Program Explanation

This C# program is used to illustrate exception handling for invalid TypeCasting in UnBoxing. Demonstrate a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

 
Runtime Test Cases
 
Specified Cast is not Valid.Error : Incorrect Boxing