# Exception

***

**1. Handling File Not Found Exception**

```csharp
try
{
    using (FileStream fs = new FileStream("myfile.txt", FileMode.Open))
    {
        // Read the file contents
    }
}
catch (FileNotFoundException ex)
{
    Console.WriteLine("File myfile.txt not found.");
}
```

**2. Handling Index Out of Range Exception**

```csharp
int[] arr = new int[5];
try
{
    arr[5] = 10;
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Index out of range.");
}
```

**3. Handling Null Reference Exception**

```csharp
Person person = null;
try
{
    Console.WriteLine(person.Name);
}
catch (NullReferenceException ex)
{
    Console.WriteLine("Object reference not set to an instance of an object.");
}
```

**4. Handling Divide by Zero Exception**

```csharp
int x = 10;
int y = 0;
try
{
    int result = x / y;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero.");
}
```

**5. Handling Format Exception**

```csharp
string input = "123.45";
try
{
    int value = int.Parse(input);
}
catch (FormatException ex)
{
    Console.WriteLine("Invalid input format.");
}
```

**6. Handling ArgumentNullException**

```csharp
public void MyMethod(string arg)
{
    if (arg == null)
    {
        throw new ArgumentNullException("arg");
    }
}
```

**7. Handling ArgumentOutOfRangeException**

```csharp
public void MyMethod(int index)
{
    if (index < 0 || index >= _array.Length)
    {
        throw new ArgumentOutOfRangeException("index");
    }
}
```

**8. Handling InvalidOperationException**

```csharp
public void MyMethod()
{
    if (_state == State.Invalid)
    {
        throw new InvalidOperationException("Invalid operation in current state.");
    }
}
```

**9. Handling TimeoutException**

```csharp
using System.Threading;

public void MyMethod()
{
    try
    {
        Thread.Sleep(10000);
    }
    catch (TimeoutException ex)
    {
        Console.WriteLine("Operation timed out.");
    }
}
```

**10. Handling NotSupportedException**

```csharp
public void MyMethod(string format)
{
    if (!SupportedFormats.Contains(format))
    {
        throw new NotSupportedException("Unsupported format: " + format);
    }
}
```

**11. Handling OperationCanceledException**

```csharp
using System.Threading;

CancellationTokenSource cts = new CancellationTokenSource();

try
{
    Thread.Sleep(10000, cts.Token);
}
catch (OperationCanceledException ex)
{
    Console.WriteLine("Operation canceled.");
}
finally
{
    cts.Dispose();
}
```

**12. Handling ObjectDisposedException**

```csharp
using System.IO;

public void MyMethod(FileStream fs)
{
    if (fs.IsClosed)
    {
        throw new ObjectDisposedException("fs");
    }
}
```

**13. Handling InvalidCastException**

```csharp
object obj = 123;
try
{
    string s = (string)obj;
}
catch (InvalidCastException ex)
{
    Console.WriteLine("Cannot cast object to string.");
}
```

**14. Handling OutOfMemoryException**

```csharp
try
{
    List<int> list = new List<int>();
    while (true)
    {
        list.Add(1);
    }
}
catch (OutOfMemoryException ex)
{
    Console.WriteLine("Out of memory.");
}
```

**15. Handling AggregateException**

```csharp
public async Task MyMethodAsync()
{
    try
    {
        await Task.WhenAll(
            Task.Run(() => { throw new Exception("Task 1 exception."); }),
            Task.Run(() => { throw new Exception("Task 2 exception."); })
        );
    }
    catch (AggregateException ex)
    {
        foreach (var innerEx in ex.InnerExceptions)
        {
            Console.WriteLine(innerEx.Message);
        }
    }
}
```

**16. Handling Custom Exception**

```csharp
public class MyCustomException : Exception
{
    public MyCustomException(string message) : base(message) { }
}

public void MyMethod()
{
    throw new MyCustomException("My custom exception message.");
}
```

**17. Creating an Exception from an Inner Exception**

```csharp
try
{
    // Inner exception
    throw new InvalidOperationException("Inner exception.");
}
catch (Exception ex)
{
    throw new Exception("Outer exception.", ex);
}
```

**18. Wrapping an Exception with an AggregateException**

```csharp
Exception[] exs = { new Exception("Ex 1"), new Exception("Ex 2") };
throw new AggregateException(exs);
```

**19. Rethrowing an Exception**

```csharp
try
{
    try
    {
        throw new Exception("Inner exception.");
    }
    catch (Exception innerEx)
    {
        throw; // Rethrow the inner exception
    }
}
catch (Exception outerEx)
{
    // Handle the outer exception
}
```

**20. Using Exception Filters**

```csharp
try
{
    throw new Exception("My exception.");
}
catch (Exception ex) when (ex.Message == "My exception.")
{
    // Handle the exception only if its message matches "My exception."
}
```

**21. Using Exception Clauses in Lambda Expressions**

```csharp
Func<int, int> myFunc = x =>
{
    try
    {
        return x * x;
    }
    catch (Exception ex)
    {
        return -1; // Handle the exception and return a default value
    }
};
```

**22. Using the Exception Operator in LINQ**

```csharp
int[] numbers = { 1, 2, 3, 0, 4, 5 };
IEnumerable<int> result = numbers.Where(x =>
{
    try
    {
        return 10 / x > 0;
    }
    catch (DivideByZeroException)
    {
        return false; // Handle the exception and return a default value
    }
});
```

**23. Using Exception Handling in Async Methods**

```csharp
async Task MyAsyncMethodAsync()
{
    try
    {
        await Task.Delay(1000);
    }
    catch (Exception ex)
    {
        // Handle the exception
    }
}
```

**24. Using the WhenAll Method to Handle Task Exceptions**

```csharp
Task task1 = Task.FromException(new Exception("Task 1 exception."));
Task task2 = Task.FromException(new Exception("Task 2 exception."));
try
{
    await Task.WhenAll(task1, task2);
}
catch (AggregateException ex)
{
    foreach (var innerEx in ex.InnerExceptions)
    {
        Console.WriteLine(innerEx.Message);
    }
}
```

**25. Using the Exception Parameter in Async Event Handlers**

```csharp
private async void MyEventHandlerAsync(object sender, EventArgs e)
{
    try
    {
        await DoSomethingAsync();
    }
    catch (Exception ex)
    {
        // Handle the exception and log it or notify the user
    }
}
```

**26. Using the Exception Object to Log Error Details**

```csharp
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Log the exception details:
    Console.WriteLine($"Message: {ex.Message}");
    Console.WriteLine($"Source: {ex.Source}");
    Console.WriteLine($"StackTrace: {ex.StackTrace}");
}
```

**27. Using the Exception Object to Build a Custom Error Message**

```csharp
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Build a custom error message:
    string errorMessage = $"An error occurred: {ex.Message}";
    // Display the error message:
    Console.WriteLine(errorMessage);
}
```

**28. Using the Exception Object to Rethrow an Exception with Additional Information**

```csharp
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Rethrow the exception with additional information:
    throw new Exception("An error occurred", ex);
}
```

**29. Using the Exception Object to Suppress the Error Dialog**

```csharp
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Suppress the error dialog:
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    // Log the exception:
    Console.WriteLine($"An error occurred: {ex.Message}");
}
```

**30. Using the Exception Object to Determine the Type of Exception**

```csharp
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Determine the type of exception:
    if (ex is ArgumentNullException)
    {
        // Handle the ArgumentNullException
    }
    else if (ex is FileNotFoundException)
    {
        // Handle the FileNotFoundException
    }
    else
    {
        // Handle other exceptions
    }
}
```

**31. Using the Exception Object to Handle Specific Exceptions**

```csharp
try
{
    // Code that may throw an exception
}
catch (ArgumentNullException ex)
{
    // Handle the ArgumentNullException
}
catch (FileNotFoundException ex)
{
    // Handle the FileNotFoundException
}
catch (Exception ex)
{
    // Handle other exceptions
}
```

**32. Using the Exception Object to Throw Custom Exceptions**

```csharp
// Define a custom exception class
public class MyCustomException : Exception
{
    public MyCustomException(string message) : base(message) { }
}

try
{
    // Code that may throw a custom exception
}
catch (MyCustomException ex)
{
    // Handle the MyCustomException
}
```

**33. Using the Exception Object to Handle Aggregate Exceptions**

```csharp
try
{
    // Code that may throw multiple exceptions
}
catch (AggregateException ex)
{
    // Handle the AggregateException
    foreach (var innerException in ex.InnerExceptions)
    {
        Console.WriteLine(innerException.Message);
    }
}
```

**34. Using the Exception Object to Handle Asynchronous Exceptions**

```csharp
async Task MyAsyncMethod()
{
    try
    {
        // Code that may throw an exception asynchronously
    }
    catch (Exception ex)
    {
        // Handle the exception asynchronously
    }
}
```

**35. Using the Exception Object to Handle Exceptions in Event Handlers**

```csharp
private void MyEventHandler(object sender, EventArgs e)
{
    try
    {
        // Code that may throw an exception in an event handler
    }
    catch (Exception ex)
    {
        // Handle the exception in the event handler
    }
}
```

**36. Using the Exception Object to Handle Exceptions in Lambda Expressions**

```csharp
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

try
{
    // Code that may throw an exception in a lambda expression
    numbers.ForEach(x => Console.WriteLine(10 / x));
}
catch (Exception ex)
{
    // Handle the exception in the lambda expression
}
```

**37. Using the Exception Object to Handle Exceptions in Threads**

```csharp
Thread thread = new Thread(() =>
{
    try
    {
        // Code that may throw an exception in a thread
    }
    catch (Exception ex)
    {
        // Handle the exception in the thread
    }
});

thread.Start();
```

**38. Using the Exception Object to Handle Exceptions in Web API**

```csharp
[HttpGet]
public async Task<IActionResult> MyApiMethod()
{
    try
    {
        // Code that may throw an exception in a Web API method
    }
    catch (Exception ex)
    {
        // Handle the exception in the Web API method
        return StatusCode(500, ex.Message);
    }
}
```

**39. Using the Exception Object to Handle Exceptions in ASP.NET Core Filters**

```csharp
public class MyExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        // Handle the exception in an ASP.NET Core filter
        context.ExceptionHandled = true;
        context.Result = new StatusCodeResult(500);
    }
}
```

**40. Using the Exception Object to Handle Exceptions in SignalR**

```csharp
public class MySignalRHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        try
        {
            // Code that may throw an exception in a SignalR hub
        }
        catch (Exception ex)
        {
            // Handle the exception in the SignalR hub
            await Clients.Caller.SendAsync("OnError", ex.Message);
        }
    }
}
```

**41. Using the Exception Object to Handle Exceptions in Blazor**

```csharp
@page "/"

@functions {
    private void HandleException(Exception ex)
    {
        // Handle the exception in a Blazor component
        Console.WriteLine(ex.Message);
    }
}

```

**42. Using the Exception Object to Handle Exceptions in EF Core**

```csharp
public async Task<IActionResult> MyControllerAction()
{
    try
    {
        // Code that may throw an exception in EF Core
        using (var context = new MyDbContext())
        {
            await context.SaveChangesAsync();
        }
    }
    catch (Exception ex)
    {
        // Handle the exception in EF Core
        return StatusCode(500, ex.Message);
    }
}
```

**43. Using the Exception Object to Handle Exceptions in MediatR**

```csharp
public class MyRequestHandler : IRequestHandler<MyRequest, MyResponse>
{
    public async Task<MyResponse> Handle(MyRequest request, CancellationToken cancellationToken)
    {
        try
        {
            // Code that may throw an exception in MediatR
            return await Task.FromResult(new MyResponse());
        }
        catch (Exception ex)
        {
            // Handle the exception in MediatR
            throw new MediatRException(ex.Message, ex);
        }
    }
}
```

**44. Using the Exception Object to Handle Exceptions in Hangfire**

```csharp
public class MyHangfireJob : IJob
{
    public void Execute(IJobCancellationToken cancellationToken)
    {
        try
        {
            // Code that may throw an exception in Hangfire
        }
        catch (Exception ex)
        {
            // Handle the exception in Hangfire
            Hangfire.JobStorage.Current.MarkAsFailed(this, ex);
        }
    }
}
```

**45. Using the Exception Object to Handle Exceptions in Azure Functions**

```csharp
public async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    try
    {
        // Code that may throw an exception in an Azure Function
        return new OkObjectResult("Success");
    }
    catch (Exception ex)
    {
        // Handle the exception in an Azure Function
        log.LogError(ex, "An error occurred while executing the function.");
        return new BadRequestObjectResult(ex.Message);
    }
}
```

**46. Using the Exception Object to Handle Exceptions in AWS Lambda**

```csharp
public class MyLambdaFunction : LambdaFunction
{
    public override async Task<Response> HandleAsync(Request request, CancellationToken cancellationToken)
    {
        try
        {
            // Code that may throw an exception in an AWS Lambda function
            return await Task.FromResult(new Response("Success"));
        }
        catch (Exception ex)
        {
            // Handle the exception in an AWS Lambda function
            return await Task.FromResult(new Response(ex.Message, 500));
        }
    }
}
```

**47. Using the Exception Object to Handle Exceptions in Google Cloud Functions**

```csharp
public class MyGoogleCloudFunction : IHttpFunction
{
    public async Task HandleAsync(HttpContext context)
    {
        try
        {
            // Code that may throw an exception in a Google Cloud Function
            await context.Response.WriteAsync("Success");
        }
        catch (Exception ex)
        {
            // Handle the exception in a Google Cloud Function
            await context.Response.WriteAsync(ex.Message, 500);
        }
    }
}
```

**48. Using the Exception Object to Handle Exceptions in Azure Durable Functions**

```csharp
public async Task RunAsync(DurableOrchestrationContext context)
{
    try
    {
        // Code that may throw an exception in an Azure Durable Function
        await context.CallActivityAsync("MyActivity", null);
    }
    catch (Exception ex)
    {
        // Handle the exception in an Azure Durable Function
        context.SetCustomStatus(ex.Message);
    }
}
```

**49. Using the Exception Object to Handle Exceptions in AWS Step Functions**

```csharp
public class MyStepFunction : StepFunction
{
    public async Task<StepFunctionResult> HandleAsync(Input input)
    {
        try
        {
            // Code that may throw an exception in an AWS Step Function
            return await Task.FromResult(new StepFunctionResult("Success"));
        }
        catch (Exception ex)
        {
            // Handle the exception in an AWS Step Function
            return await Task.FromResult(new StepFunctionResult(ex.Message, null, 500));
        }
    }
}
```

**50. Using the Exception Object to Handle Exceptions in Google Cloud Workflows**

```csharp
public class MyWorkflow : Workflow
{
    public async Task<WorkflowResult> HandleAsync(WorkflowRequest request)
    {
        try
        {
            // Code that may throw an exception in a Google Cloud Workflow
            return await Task.FromResult(new WorkflowResult("Success"));
        }
        catch (Exception ex)
        {
            // Handle the exception in a Google Cloud Workflow
            return await Task.FromResult(new WorkflowResult(ex.Message, null, 500));
        }
    }
}
```
