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.");
}
}
}
OutputError: 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#
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.
Similar Reads
Ruby | Exceptions
A good program(or programmer) predict error and arrange to handle them in an effective manner. This is not as easy as it sounds. Exceptions are the errors that occur at runtime. It halts the execution of a program. They are caused by an extensive variety of exceptional circumstances, such as running
4 min read
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
Python Built-in Exceptions
In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error.We can catch exceptions using try and
8 min read
Errors V/s Exceptions In Java
In Java, errors and exceptions are both types of throwable objects, but they represent different types of problems that can occur during the execution of a program. Errors are usually caused by serious problems that are outside the control of the program, such as running out of memory or a system cr
5 min read
fegetexceptflag() function in C/C++
The fegetexceptflag() function in C/C++ is specified in header file fenv.h and gets floating point exception flags. This function store the raised exception in the point specified by flagp . Syntax: int fegetexceptflag(fexcept_t* flagp, int excepts) Parameters: The function accepts two mandatory par
2 min read
exception::what() in C++ with Examples
The exception::what() used to get string identifying exception. This function returns a null terminated character sequence that may be used to identify the exception. Below is the syntax for the same: Header File: #include<exception> Syntax: virtual const char* what() const throw(); Return: Th
2 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
feclearexcept in C++ with Examples
feclearexcept() clears the supported floating-point exceptions represented by excepts. Syntax: int feclearexcept(int excepts); excepts : Bitmask listing of exception flags to clear Return value: The feclearexcept() function returns zero value if all the exceptions were cleared or if excepts is equal
1 min read
fegetenv() function in C/C++
The fegetenv() function in C/C++ is specified in header file cfenv.h and attempts to store the current state of the floating-point environment in the object pointed by envp. The floating point environment is a set of status flags and control modes which includes both floating point exception and the
4 min read
feupdateenv() function in C++
The feupdateenv() function in C++ first saves currently raised floating-point exceptions. It restores the floating-point environment from the given fenv_t object and then raises the exceptions which were saved previously.Syntax: int feupdateenv( fenv_t* envp ) Parameters: It accepts a single mandato
2 min read