Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
Exception Handling in Programming
Next article icon

C# Program that Demonstrates Exception Handling For Invalid TypeCasting in UnBoxing

Last Updated : 01 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  1. 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. 
  2. 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.
  3. 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.

Syntax:

try{

      // Statements

}

catch{

     // Handle the exception

}

finally{

    // 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.

Syntax:

(datatype)variable/object;

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.

Example:

Input  : 50  Output : Specified cast is not valid.

Approach:

  1. Declare an integer variable named "number".
  2. Convert that variable to the object(This is known as Unboxing).
  3. Convert the integer variable into short data type in try block.
  4. Handle the exception in catch block.

Example:

C#
// C# program to illustrate how to exception handling  // for invalid TypeCasting in unBoxing using System; class GFG{      static void Main() {          // Declare a number     int number = 50;          // Set this number to the object     object object1 = number;      try     {                  // Type cast this object to short         int x = (short)object1;          System.Console.WriteLine("Unboxing the object");     }          // Handle exception     catch (System.InvalidCastException e)     {                  // Display the error message         System.Console.WriteLine(e.Message);     } } } 

Output:

Specified cast is not valid.

Next Article
Exception Handling in Programming
author
gottumukkala_sivanagulu
Improve
Article Tags :
  • C#
  • CSharp-Exception-Handling
  • CSharp-programs

Similar Reads

  • Exception Handling in Programming
    Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we'll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
    7 min read
  • C# Program to Demonstrate the Use of FailFast() Method of Environment Class
    Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environme
    3 min read
  • Exception handling in Objective-C
    Exception handling is an essential aspect of Objective-C programming, enabling developers to manage unforeseen errors effectively. Objective-C provides a robust set of tools and methodologies to handle exceptions, ensuring the stability and reliability of applications. Let's delve deeper into the nu
    5 min read
  • How to Fix java.lang.classcastexception in Java?
    ClassCastException in Java occurs when we try to convert the data type of entry into another. This is related to the type conversion feature and data type conversion is successful only where a class extends a parent class and the child class is cast to its parent class. Here we can consider parent c
    6 min read
  • Error Handling in Programming
    In Programming, errors occur. Our code needs to be prepared for situations when unexpected input from users occurs, division by zero occurs, or a variable name is written incorrectly. To prevent unexpected events from crashing or having unexpected outcomes, error handling involves putting in place m
    12 min read
  • How to detect Stack Unwinding in a Destructor in C++?
    What is Stack Unwinding? Stack unwinding is the process of executing destructors for all local objects when an exception propagates out of a function. It happens when an exception is thrown and not caught within the same function. When this occurs, the destructors for all objects with automatic stor
    4 min read
  • Exception handling in Julia
    Any unexpected condition that occurs during the normal program execution is called an Exception. Exception Handling in Julia is the mechanism to overcome this situation by chalking out an alternative path to continue normal program execution. If exceptions are left unhandled, the program terminates
    6 min read
  • How to Solve Class Cast Exceptions in Java?
    An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote fi
    3 min read
  • Difference between Boxing and Unboxing in C#
    Boxing and unboxing is an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, it converts a Value Type to a Reference Type, and vice versa. Boxing and Unboxing enables a unified view of the type syste
    2 min read
  • Concrete Exceptions in Python
    In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences