A repository of exercises to support the training.
In this module, you will learn how to raise and handle exceptions effectively in C#. You will explore exception handling in both sequential and parallel programs, gaining insights into best practices for robust application development.
In a futuristic city's energy management system, exceptions may occur due to invalid configurations or resource constraints. This exercise demonstrates how to handle such errors in a sequential program.
Instructions:
try-catch
block to manage the error gracefully and log the details.using System;
class Program
{
static void Main(string[] args)
{
try
{
SimulateEnergyLoad(-1);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void SimulateEnergyLoad(int load)
{
if (load < 0)
{
throw new ArgumentException("Load value cannot be negative.");
}
Console.WriteLine($"Energy load set to {load} units.");
}
}
Expected Outcome:
try-catch
.Parallel tasks in the futuristic city might fail independently. This exercise explores how to aggregate and handle exceptions that occur during parallel execution.
Instructions:
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
try
{
Parallel.For(0, 5, i =>
{
if (i % 2 == 0)
{
throw new InvalidOperationException($"Task {i} failed.");
}
Console.WriteLine($"Task {i} completed successfully.");
});
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
{
Console.WriteLine($"Caught exception: {ex.Message}");
}
}
}
}
Expected Outcome:
Next Steps: