C Sharp_Exception Handling
C Sharp_Exception Handling
Exception handling is crucial for managing errors in your applications gracefully without crashing. In C#, exception
handling is done using try , catch , finally , and custom exceptions. Below are real-time examples of
exception handling concepts in C#.
1. Exception Handling in C#
Exception Handling in C# allows developers to handle runtime errors using try , catch , and finally blocks.
The try block contains the code that may throw an exception, the catch block handles the exception, and the
finally block contains cleanup code that always runs, regardless of whether an exception occurred.
Explanation:
If the user enters a non-numeric value, the FormatException is caught.
If the user enters 0 , a DivideByZeroException is caught.
The finally block runs no matter what, displaying a message to indicate that the execution is complete.
Explanation:
FormatException is caught if the user enters a non-numeric value.
DivideByZeroException is caught if the user tries to divide by zero.
Explanation:
The finally block ensures that cleanup actions (like closing files) occur even if an error occurs during
execution.
Explanation:
The InvalidAgeException class inherits from Exception and provides a custom error message. If
an invalid age is encountered, the custom exception is thrown.
5. Inner Exception in C#
Inner Exception: An inner exception provides more details about an exception that caused the current exception. It
can be accessed using the InnerException property.
Example: Using Inner Exception
using System; csharp
Explanation:
An InvalidOperationException is thrown and caught in the inner try block. The exception is
rethrown as a general Exception with the InvalidOperationException as its inner exception. This
provides detailed information about the original error.
Explanation:
In this case, an exception is thrown and caught when the user enters a negative number. However, using
exceptions for business logic (such as validating input) is generally considered poor practice because it can
lead to unnecessary performance overhead.
Instead, validation should be done without exceptions, such as through simple if conditions.