C# Program that Demonstrates Exception Handling For Invalid TypeCasting in UnBoxing
Exception handling is used to handle the errors in the program. Or we can say that an exception is an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of the occurrence of an exception are not known to the program. In this situation, we can create an exception object and call the exception handler code. This exception handler saves the program from the crash and this process is known as exception handling. Exception handling is necessary because it handles an unwanted event so that the program code still makes sense to the user. We can achieve this by using try and catch block
- try: This block identifies a block of code for which any errors are there. If there is any error then it will send to catch block. It can contain one or more catch block and this block is created using try keyword.
- catch: This block is used to handle the error raised in the try block. The catch keyword is used for catch block. For the catch block, there should be definitely a try block.
- finally: This block is used to run the specified set of statements, whether an exception is thrown or not thrown. It is an optional block and created by using the finally keyword.
// Handle the exception
// Finally block
Typecasting can be defined as the process of converting the variable from one data type to another. If the data types are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to be converted explicitly which is known as Explicit Type conversion.
Here, the data type is the type of data that we type case, For example, we can convert Integer type to Short type.
Here in this article, we have to handle the Typecasting integer to short data type and we are going to handle that exception.
Input : 50 Output : Specified cast is not valid.
- Declare an integer variable named “number”.
- Convert that variable to the object(This is known as Unboxing).
- Convert the integer variable into short data type in try block.
- Handle the exception in catch block.
Specified cast is not valid.