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:
C# - Nesting of Try and Catch Blocks
Next article icon

C# Exceptions

Last Updated : 25 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An exception in C# is an unwanted or unexpected event that occurs at runtime. It affects the normal flow of the program. Common exceptions include invalid input, divide-by-zero operations, or accessing invalid array indices. C# provides a powerful exception-handling mechanism to successfully recover from these runtime issues and keep the program running smoothly.

Example: Divide By Zero Exception. This example shows the occurrence of the exception during divide by zero operation.

C#
// C# program to illustrate the exception using System; class Geeks {      static void Main(string[] args)     {          // Declaring two integer values         int A = 12;         int B = 0;          // divide by zero error         int C = A / B;          Console.Write("Value of C is " + C);     } } 

Output:

Unhandled Exception:
System.DivideByZeroException: Attempted to divide by zero.
at Geeks.Main (System.String[] args) [0x00005] in <78d30a8ae7274e28ac400780dfde8dc7>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.DivideByZeroException: Attempted to divide by zero.
at Geeks.Main (System.String[] args) [0x00005] in <78d30a8ae7274e28ac400780dfde8dc7>:0

Exception Handling in C#

C# provides try-catch and finally blocks to handle exceptions effectively.

Syntax:

try

{

// Code that may throw an exception

}

catch (ExceptionType ex)

{

// Handle the exception

}

finally

{

// Cleanup code (optional)

}

Example:

C#
using System;  class Geeks {     static void Main()     {         try         {             int A = 10;             int B = 0;              // Attempting to divide by zero             int res = A / B;             Console.WriteLine("Result: " + res);         }         catch (DivideByZeroException ex)         {             Console.WriteLine("Error: " + ex.Message);         }         finally         {             Console.WriteLine("Execution completed.");         }     } } 

Output
Error: Attempted to divide by zero. Execution completed. 

C# Exception Hierarchy

In C#, all exceptions are derived from the base class Exception, which is further divided into two main categories:

  • SystemException: This is the base class for exceptions generated by the Common Language Runtime (CLR) or system-related errors. Examples include DivideByZeroException and NullReferenceException.
  • ApplicationException: This is the base class for exceptions related to the application. Developers can create custom exception types by inheriting from ApplicationException.

All exception classes in C# are ultimately derived from the Exception class, with SystemException containing standard system-related exceptions and ApplicationException allowing users to define their own specific exceptions. To know the difference between these, refer: System Level Exception Vs Application Level Exception in C#

Exception Class Hierarchy

Difference Between Errors and Exception

Features

Errors

Exceptions

Definition

Errors are unexpected issues that may arise during computer program execution.

Exceptions are unexpected events that may arise during run-time.

Handling

Errors cannot be handled by the Program.

Exceptions can be handled using try-catch mechanisms.

Relationship

All Errors are exceptions.

All exceptions are not errors.

C# Exception Classes

There are different kinds of exceptions which can be generated in C# program:

1. Divide By Zero exception: It occurs when the user attempts to divide by zero.

Example:

int result = 10 / 0; // Throws DivideByZeroException

2. NullReferenceException: Occurs when referencing a null object.

Example:

string str = null;

Console.WriteLine(str.Length); // Throws NullReferenceException

3. IndexOutOfRangeException: Thrown when accessing an invalid index in an array.

Example:

int[] arr = {1, 2, 3};

Console.WriteLine(arr[5]); // Throws IndexOutOfRangeException

4. OutOfMemoryException: Occurs when the program exceeds available memory.

5. StackOverflowException: Caused by infinite recursion.

Example:

void Recursive() => Recursive();

Recursive(); // Throws StackOverflowException

Properties of the Exception Class

The Exception class has many properties which help the user to get information about the exception during the exception.

  • Data: This property helps to get the information about the arbitrary data which is held by the property in the key-value pairs.
  • TargetSite: This property helps to get the name of the method where the exception will throw.
  • Message: This property helps to provide the details about the main cause of the exception occurrence.
  • HelpLink: This property helps to hold the URL for a particular exception.
  • StackTrace: This property helps to provide the information about where the error occurred.
  • InnerException: This property helps to provide the information about the series of exceptions that might have occurred.

Important Points:

  • Use Specific Exceptions: Catch specific exceptions rather than a general Exception.

catch (DivideByZeroException ex) { /* Handle divide-by-zero */ }

  • Avoid Empty Catch Blocks: Always log or handle exceptions meaningfully.
  • Use Finally for Cleanup: Use the finally block to release resources like files or database connections.
  • Do Not Overuse Exceptions: Use exceptions only for exceptional cases, not for control flow.


Next Article
C# - Nesting of Try and Catch Blocks
author
alpha_786
Improve
Article Tags :
  • C#
  • CSharp-Exception

Similar Reads

  • Exception Handling in C#
    An exception is defined as 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 occurrence of an exception is not known to the program. In such a case, we create an exception object and call the exception handler code.
    6 min read
  • C# | Array IndexOutofRange Exception
    C# supports the creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the C# t
    3 min read
  • C# System Level Exception vs Application Level Exception
    In C#, exceptions are categorized into two main types based on their origin and usage, which are System-level exceptions and Application-level exceptions. Understanding the difference between these two helps in managing exceptions properly and choosing the right exception-handling approach. System L
    3 min read
  • How to Use Multiple Catch Clauses in C#?
    In C#, the main purpose of a catch block is to handle exceptions raised in the try block. A catch block is executed only when an exception occurs in the program. We can use multiple catch blocks with a single try block to handle different types of exceptions. Each catch block is designed to handle a
    3 min read
  • C# - Nesting of Try and Catch Blocks
    In C#, the nesting of the try-and-catch block is allowed. The nesting of a try block means one try block can be nested into another try block. The various programmer uses the outer try block to handle serious exceptions, whereas the inner block for handling normal exceptions. Example 1: Handling Div
    3 min read
  • C# finally Keyword
    finally keyword in C# is an important component of exception handling. It makes sure that specific cleanup code is always executed, whether an exception is thrown or not. This makes it ideal for releasing resources such as file handles, database connections, or network streams. The finally block is
    4 min read
  • 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 thi
    3 min read
  • C# Jump Statements (Break, Continue, Goto, Return and Throw)
    In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#. Types of Jump StatementsThere are mainly five keywords in t
    4 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
  • C# Program to Demonstrate the Use of Exit() Method of Environment Classhttps://origin.geeksforgeeks.org/?p=705454
    Environment Class provides information about the current platform and manipulates, the current platform. The Environment class 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 inf
    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