Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

C Sharp_Exception Handling

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C Sharp_Exception Handling

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Real-Time Examples of Exception Handling in C#

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.

Example: Basic Exception Handling


using System; csharp

public class Program


{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine()); // May throw FormatException
int result = 10 / num; // May throw DivideByZeroException
Console.WriteLine("Result: " + result);
}
catch (FormatException ex)
{
Console.WriteLine("Invalid input! Please enter a valid number.");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
catch (Exception ex) // Catch all other exceptions
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
Console.WriteLine("Execution completed. Thank you!");
}
}
}

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.

2. Multiple Catch Blocks in C#


Multiple Catch Blocks: C# allows multiple catch blocks to handle different types of exceptions separately. Each
catch block handles a specific exception type.

Example: Handling Multiple Exceptions


using System; csharp

public class Program


{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter the first number:");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number:");
int num2 = Convert.ToInt32(Console.ReadLine());

int result = num1 / num2; // May throw DivideByZeroException


Console.WriteLine("Result: " + result);
}
catch (FormatException ex)
{
Console.WriteLine("Input is not a valid number!");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
catch (Exception ex)
{
Console.WriteLine("Unexpected error: " + ex.Message);
}
}
}

Explanation:
FormatException is caught if the user enters a non-numeric value.
DivideByZeroException is caught if the user tries to divide by zero.

The general Exception block catches all other unhandled exceptions.


3. Finally Block in C#
Finally Block: The finally block in C# is always executed, regardless of whether an exception was thrown or not.
It is used for cleanup activities such as closing files or releasing resources.
Example: Using Finally Block
using System; csharp

public class Program


{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Attempting to open file...");
// Simulating file opening
throw new Exception("File not found");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("Closing file, cleanup actions...");
}
}
}

Explanation:
The finally block ensures that cleanup actions (like closing files) occur even if an error occurs during
execution.

4. How to Create Custom Exceptions in C#


Custom Exceptions: You can create your own exception types in C# by deriving from the Exception class. This
allows you to throw and catch application-specific exceptions.
Example: Creating a Custom Exception
using System; csharp

// Custom Exception class


public class InvalidAgeException : Exception
{
public InvalidAgeException(string message) : base(message) { }
}
public class Program
{
public static void Main(string[] args)
{
try
{
int age = -1; // Invalid age
if (age < 0)
{
throw new InvalidAgeException("Age cannot be negative!");
}
Console.WriteLine("Age: " + age);
}
catch (InvalidAgeException ex)
{
Console.WriteLine("Custom Error: " + ex.Message);
}
}
}

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

public class Program


{
public static void Main(string[] args)
{
try
{
try
{
throw new InvalidOperationException("Invalid operation.");
}
catch (InvalidOperationException ex)
{
throw new Exception("An error occurred in the operation.", ex); // Wra
pping the inner exception
}
}
catch (Exception ex)
{
Console.WriteLine("Outer Exception: " + ex.Message);
Console.WriteLine("Inner Exception: " + ex.InnerException?.Message);
}
}
}

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.

6. Exception Handling Abuse in C#


Exception Handling Abuse: This occurs when exceptions are used for control flow or when exception handling is
done inappropriately (e.g., catching all exceptions without any meaningful handling). Overusing exceptions can lead to
performance overhead and make the code harder to maintain.
Example: Exception Handling Abuse
using System; csharp

public class Program


{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());
// Doing some business logic
if (num < 0)
{
throw new Exception("Negative number is not allowed");
}
Console.WriteLine("You entered: " + num);
}
catch (Exception ex)
{
// Handling all exceptions, even for business logic
Console.WriteLine("Error: " + ex.Message);
}
}
}

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.

Summary of Key Points:


1. Exception Handling: Allows graceful error handling using try , catch , and finally blocks.
2. Multiple Catch Blocks: You can catch different types of exceptions separately to provide specific error handling
for each.
3. Finally Block: Ensures that code (e.g., cleanup tasks) always runs, regardless of whether an exception occurred.
4. Custom Exceptions: Allows creating your own exception classes for application-specific error handling.
5. Inner Exception: Helps provide detailed error information by including the original exception within a new
exception.
6. Exception Handling Abuse: Should be avoided by not using exceptions for normal control flow or business logic
validation.
Exception handling, when used correctly, can help maintain application stability by managing unexpected situations. It
also provides more control over error handling in your application, improving the user experience and system reliability.

You might also like