Loading...

OBJECT ORIENTED PROGRAMMING  

>

LEARNING OUTCOME 5

IMPLEMENT EXCEPTION HANDLING, DECISION MAKING AND FLOW CONTROL IN C# PROGRAM

UNDERSTANDING EXCEPTIONS IN C# PROGRAMS

EXCEPTIONS:

Types of Exceptions:

DISTINGUISHING BETWEEN ERRORS AND EXCEPTIONS:

Code Example (Handling a Potential Divide-by-Zero Exception):

C#
		using System;
		public class Example
		{
			public static void Main()
			{
				int numerator = 10;
				int denominator = 0; // Potentially problematic
				try
				{
					int result = numerator / denominator; // Could throw a DivideByZeroException
					Console.WriteLine("Result: {0}", result);
				}
				catch (DivideByZeroException ex)
				{
					Console.WriteLine("Error: Division by zero attempted.");
					Console.WriteLine("Exception details: {0}", ex.Message);
				}
				Console.WriteLine("Program execution continues.");
			}
		}
		

EXCEPTION HANDLING

Importance of Exception Handling:

EXCEPTION HIERARCHY

Example (Custom Exception):

C#
		public class InvalidDataFormatException : Exception
		{
			public InvalidDataFormatException(string message) : base(message)
			{
			}
		}
		public class MyProcessor
		{
			public void ProcessData(string data)
			{
				try
				{
					// Data processing logic (potentially throwing an exception)
					if (!ValidateData(data))
					{
						throw new InvalidDataFormatException("Data format is invalid.");
					}
				}
				catch (InvalidDataFormatException ex)
				{
					Console.WriteLine("Error: {0}", ex.Message);
					// Handle invalid data format (e.g., log the error, provide user instructions)
				}
			}
			private bool ValidateData(string data)
			{
				// Implement data validation logic
				return true; // Replace with actual validation
			}
		}
		

TYPES OF EXCEPTIONS:

In C#, exceptions are mechanisms for handling unexpected errors or conditions that disrupt the normal flow of program execution. They provide a controlled way to catch and address these errors, preventing program crashes and improving code robustness. Here's a breakdown of types and classes:

Types of Exceptions:

Exception Hierarchy:

C# follows a hierarchical structure for exceptions, providing a classification system for different error conditions. This hierarchy helps in organizing and handling exceptions effectively.

Example (Custom Exception):

C#
public class InvalidDataFormatException : Exception
{
    public InvalidDataFormatException(string message) : base(message)
    {
    }
}

Why Use Exceptions?

Choosing the Right Exception:

CREATING USER-DEFINED EXCEPTIONS IN C#

User-defined exceptions are a powerful way to handle errors specific to your application's domain logic. They provide more meaningful error messages and allow for targeted error handling compared to relying solely on system-generated exceptions. [Youtube Tutorials can be used as an additional resource for further study and understanding- refer to Tinashe Kunyadini (+27 62 968 4556)]

Here's a step-by-step process for creating user-defined exceptions in C#:

  1. Inherit from System.Exception:
    C#
    public class MyCustomException : Exception
    {
        // ... your custom exception details here
    }
    
  2. Define Constructors (Optional):
    • While not mandatory, you can define constructors for your custom exception class. These constructors allow you to provide additional information about the error when creating an instance of the exception. Common constructors include:
    • A default constructor with no arguments:
      C#
      public MyCustomException() { }
      
    • A constructor with a message string:
      C#
      public MyCustomException(string message) : base(message) { }
      
    • A constructor with a message string and an inner exception:
      C#
      public MyCustomException(string message, Exception innerException) :
      base(message, innerException) { }
      

      The innerException parameter allows you to specify another exception that caused your custom exception.

  3. Add Properties (Optional):

    You can define properties in your custom exception class to store additional information about the error. This information can be accessed in the catch block when the exception is handled.

    C#
    public class InvalidDataFormatException : Exception
    {
        public string InvalidData { get; private set; }
        public InvalidDataFormatException(string message, string invalidData) : base(message)
        {
            InvalidData = invalidData;
        }
    }
    
  4. Throw the Exception:
    C#
    if (data.Length == 0)
    {
        throw new InvalidDataFormatException("Data cannot be empty.", data);
    }
    
  5. Handle the Exception:
    C#
    try
    {
        ProcessData(data);
    }
    catch (InvalidDataFormatException ex)
    {
        Console.WriteLine("Error: {0}", ex.Message);
        Console.WriteLine("Invalid data: {0}", ex.InvalidData); // If the property exists
        // Perform other error handling actions (e.g., logging, user notification)
    }
    

Best Practices:

EXCEPTION HANDLING PROCEDURES IN C#

Exception handling in C# is a crucial technique for managing unexpected errors and preventing program crashes. Here's a breakdown of the procedure:

  1. Identify Potential Exceptions:
    • Analyze your code to identify possible scenarios where errors or invalid conditions might arise.
    • Consider common system-generated exceptions (e.g., NullReferenceException, IndexOutOfRangeException) and errors specific to your application logic.
  2. Use try...catch Blocks:
    • The try...catch block is the fundamental construct for handling exceptions.
    • The try block encloses the code that might throw an exception.
    • One or more catch blocks follow the try block to handle different types of exceptions.

    Example:

    C#
    try
    {
     int result = numerator / denominator;
     Console.WriteLine("Result: {0}", result);
    }
    catch (DivideByZeroException ex)
    {
     Console.WriteLine("Error: Division by zero attempted.");
    }
    catch (Exception ex) // Catch-all for other exceptions (optional)
    {
     Console.WriteLine("An unexpected error occurred: {0}", ex.Message);
    }
    
  3. Exception Handling in catch Blocks:
    • Each catch block specifies the type of exception it can handle.
    • Within the catch block, you can perform actions like:
      • Printing error messages to the console or a log file.
      • Displaying user-friendly error notifications.
      • Taking corrective actions to recover from the error (if possible).
      • Re-throwing the exception (advanced scenario using throw).
  4. Prioritize catch Blocks:
    • List more specific exception types before more general ones.
    • For example, place a catch block for DivideByZeroException before a general catch block for Exception.
    • The first matching catch block is executed if an exception is thrown within the try block.
  5. Optional finally Block:
    • The finally block (optional) is always executed, regardless of whether an exception is thrown or not.
    • Use it for code that needs to run unconditionally, such as closing resources (files, database connections) opened within the try block.

    Example:

    C#
    StreamReader reader = null;
    try
    {
     reader = new StreamReader("myfile.txt");
     // Read from the file
    }
    catch (FileNotFoundException ex)
    {
     Console.WriteLine("File not found: {0}", ex.Message);
    }
    finally
    {
     if (reader != null)
     {
     reader.Close(); // Ensure file is closed even if an exception occurs
     }
    }
    

Best Practices:

PROGRAMMING CONSTRUCTS IN C#

Programming constructs are the fundamental building blocks of any programming language. They provide a structured way to organize code, control its flow, and define reusable components. In C#, these constructs offer a rich set of tools for writing well-organized, efficient, and maintainable programs.

TYPES OF PROGRAMMING CONSTRUCTS in C#:

IMPORTANCE OF PROGRAMMING CONSTRUCTS:

Example (Using Multiple Constructs):

C#
int age = 25; // Data type and variable
string name = "Alice";
if (age >= 18) // Control flow (if statement)
{
 Console.WriteLine(name + " is eligible to vote.");
}
else
{
 Console.WriteLine(name + " is not yet eligible to vote.");
}

THREE FUNDAMENTAL PROGRAMMING CONSTRUCTS

While there are more than three fundamental programming constructs, here are three core ones that are essential for building any program:

  1. Sequence:
    • The most basic construct, sequence simply refers to a series of statements executed one after another in the order they appear in the code.
    • This forms the linear execution path of your program.

    Example (C#):

    C#
    int x = 10;
    int y = 20;
    int sum = x + y;
    Console.WriteLine("The sum is: {0}", sum);
    

    In this example, each line of code is executed sequentially:

    • x is assigned the value 10.
    • y is assigned the value 20.
    • The sum of x and y is calculated and stored in sum.
    • The value of sum is printed to the console.
  2. Selection (Decision Making):
    • Selection constructs allow your program to make choices based on conditions.
    • Common selection statements include if...else, switch, and ternary operator (?:).

    Example (C#):

    C#
    int age = 25;
    if (age >= 18) {
     Console.WriteLine("You are eligible to vote.");
    } else {
     Console.WriteLine("You are not eligible to vote.");
    }
    

    Here, the program checks if age is greater than or equal to 18. If true, it prints one message, otherwise it prints another.

  3. Repetition:
    • Repetition constructs enable code to be executed multiple times, often based on a specific condition.
    • Common repetition statements include for, while, and do...while loops.

    Example (C#):

    C#
    for (int i = 0; i < 5; i++) {
     Console.WriteLine("Iteration: {0}", i);
    }
    

    This code iterates five times, printing the current iteration number (i) in each loop.

These three core constructs (sequence, selection, repetition) are the foundation for building more complex program logic by combining them in various ways. Additional constructs like functions, classes, and exception handling further enhance program structure, modularity, and error management.

SELECTION (DECISION MAKING) in C# Programs

Selection constructs, also known as decision-making statements, are a fundamental feature in any programming language. They allow your program to take different paths based on specific conditions. This enables your code to be more adaptable and responsive to varying input or program state.

Types of Selection Statements in C#:

IMPORTANCE OF SELECTION IN PROGRAMMING:

Example (Using if...else and switch):

C#
int age = 25;
string grade = "B";
if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are not an adult.");
}
switch (grade)
{
    case "A":
        Console.WriteLine("Excellent work!");
        break;
    case "B":
        Console.WriteLine("Good job.");
        break;
    case "C":
        Console.WriteLine("You can do better.");
        break;
    default:
        Console.WriteLine("Invalid grade.");
        break;
}

In this example:

In C#, selection statements, also known as decision-making statements, control the flow of your program based on certain conditions. Here's a breakdown of the common types, focusing on clarifying the difference between single and double selection:

1. Single Selection (if Statement):

C#
if (condition)
{
    // code to execute if the condition is true
}
C#
int number = 10;
if (number > 0)
{
    Console.WriteLine("The number is positive.");
}

In this example, the code inside the if block will only be executed if number is greater than 0.

3. Double Selection (if...else Statement):

C#
if (condition)
{
    // code to execute if the condition is true
}
else
{
    // code to execute if the condition is false
}
C#
int age = 25;
if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are not an adult.");
}

Here, the if block executes if age is 18 or older, while the else block executes if the condition is false.

Key Difference:

Additional Selection Types:

Summary:

MULTIPLE SELECTION AND NESTED SELECTION IN C#

Beyond single and double selection, C# offers additional constructs for handling more complex decision-making logic:

1. Multiple Selection (switch Statement):

C#
switch (expression)
{
    case value1:
        // code to execute if expression equals value1
        break;
    case value2:
        // code to execute if expression equals value2
        break;
    // ... more cases
    default:
        // code to execute if expression doesn't match any case
        break;
}
C#
char grade = 'B';
switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent work!");
        break;
    case 'B':
        Console.WriteLine("Good job.");
        break;
    case 'C':
        Console.WriteLine("You can do better.");
        break;
    default:
        Console.WriteLine("Invalid grade.");
        break;
}

In this example, the switch statement evaluates the grade variable and provides feedback based on its value.

2. Nested Selection:

C#
int age = 25;
bool isCitizen = true;
if (age >= 18)
{
    if (isCitizen)
    {
        Console.WriteLine("You are eligible to vote.");
    }
    else
    {
        Console.WriteLine("You are not eligible to vote (not a citizen).");
    }
}
else
{
    Console.WriteLine("You are not eligible to vote (under 18).");
}

Here, the outer if statement checks if age is 18 or older. If true, an inner if...else block checks the isCitizen flag to determine final eligibility for voting.

Choosing the Right Construct:

Remember:

ITERATION (REPETITION) in C# Programs

Iteration, also known as repetition, is a fundamental concept in programming that allows a block of code to be executed multiple times. This is essential for tasks involving processing sequences of data, performing calculations repeatedly, or creating control loops.

Types of Iteration Statements in C#:

Importance of Iteration in Programming:

Example (Using for and while Loops):

C#
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}
string input = "";
while (input.ToLower() != "exit")
{
    Console.Write("Enter a word (or 'exit' to quit): ");
    input = Console.ReadLine();
    if (input.ToLower() != "exit")
    {
        Console.WriteLine("You entered: {0}", input);
    }
}

In this example:

Choosing the Right Iteration Statement:

Best Practices:

Here's another example code that demonstrates the use of a while loop and user input validation in C#:

C#
public class GuessingGame
{
    public static void Main(string[] args)
    {
        int secretNumber = new Random().Next(1, 101); // Generate random number between 1 and 100
        int guess;
        int numGuesses = 0;
        Console.WriteLine("Welcome to the Guessing Game!");
        do
        {
            // Get valid user input (number between 1 and 100)
            do
            {
                Console.Write("Guess a number between 1 and 100: ");
            } while (!int.TryParse(Console.ReadLine(), out guess) || guess < 1 || guess > 100);
            numGuesses++;
            if (guess > secretNumber)
            {
                Console.WriteLine("Too high! Guess again.");
            }
            else if (guess < secretNumber)
            {
                Console.WriteLine("Too low! Guess again.");
            }
        } while (guess != secretNumber);
        Console.WriteLine("Congratulations! You guessed the number in {0} tries.", numGuesses);
    }
}

The do...while Loop in C#

The do...while loop is a fundamental iteration statement in C# that allows a block of code to execute at least once, followed by repeated executions as long as a specified condition remains true.

Syntax:

C#
do
{
    // code to be executed
} while (condition);

Key Points:

Example:

C#
int number = 0;
do
{
    Console.WriteLine("Enter a positive integer: ");
    number = int.Parse(Console.ReadLine()); // Read user input and convert to integer
} while (number <= 0); // Keep looping until a positive number is entered
Console.WriteLine("You entered: {0}", number);

When to Use do...while:

Remember:

The while Loop in C#

The while loop is a fundamental iteration statement in C# that allows a block of code to be executed repeatedly as long as a specified condition remains true.

Syntax:

C#
while (condition)
{
    // code to be executed
}

Key Points:

Example:

C#
int count = 1;
while (count <= 5)
{
    Console.WriteLine("Count: {0}", count);
    count++; // Increment count by 1
}

When to Use while:

Remember:

The for Loop in C#

The for loop is a versatile iteration statement in C# used for a predefined number of iterations. It combines initialization, condition checking, and increment/decrement steps into a concise syntax.

Syntax:

C#
for (initialization; condition; increment/decrement)
{
    // code to be executed
}

Key Points:

Example:

C#
for (int i = 1; i <= 5; i++) // i = 1, i <= 5, i++
{
    Console.WriteLine("Iteration: {0}", i);
}

When to Use for Loops:

Additional Features:

Remember:

By mastering the for loop, you can write clear and efficient programs in C# that handle repetitive tasks with a predetermined number of iterations.

The foreach Loop in C#

Is specifically designed for iterating over elements in collections (like arrays and lists) without a counter variable:

The foreach loop, also known as the "for each" loop, is a powerful iteration construct in C# that simplifies iterating through elements of a collection. It provides a more concise and readable way to access each element in the collection without managing a loop counter variable.

Syntax:

C#
foreach (var element in collection)
{
 // code to be executed for each element
}

Explanation:

Example:

C#
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
 Console.WriteLine("Hello, {0}!", name);
}

In this example:

Key Points:

When to Use foreach Loops:

Additional Considerations:

Here's another example that might appear in exams or interviews:

Demonstrating how to use a foreach loop to calculate the average of numbers in an array:

C#
int[] numbers = { 10, 20, 30, 40, 50 };
double sum = 0;
foreach (int number in numbers)
{
 sum += number; // Add each element to the sum
}
double average = sum / (double)numbers.Length; // Calculate average
Console.WriteLine("The average of the numbers is: {0:F2}", average);

Why foreach is preferred here:

This example showcases:

A typical use case for foreach loops in interviews or exams, where you need to iterate through elements in a collection and perform some operation on them.

EXAMPLES

Reversing a String:

This example demonstrates using a for loop to reverse a string character by character:

C#
string originalString = "Hello World!";
string reversedString = "";
for (int i = originalString.Length - 1; i >= 0; i--)
{
 reversedString += originalString[i];
}
Console.WriteLine("Original String: {0}", originalString);
Console.WriteLine("Reversed String: {0}", reversedString);

Finding the Maximum Value in an Array:

This example showcases using a while loop to find the maximum element in an integer array:

C#
int[] numbers = { 5, 12, 3, 18, 7 };
int maxValue = numbers[0]; // Assume first element as initial max
int i = 1;
while (i < numbers.Length)
{
 if (numbers[i] > maxValue)
 {
 maxValue = numbers[i];
 }
 i++;
}
Console.WriteLine("The maximum value in the array is: {0}", maxValue);

Summing Elements in a List:

This example demonstrates using a foreach loop to calculate the sum of elements in a List:

C#
List numbers = new List() { 2, 4, 6, 8 };
int sum = 0;
foreach (int number in numbers)
{
 sum += number;
}
Console.WriteLine("The sum of the elements in the list is: {0}", sum);

BREAK AND CONTINUE STATEMENTS IN C# LOOPS

The break and continue statements are essential control flow statements used within loops in C# to modify the loop's execution flow.

1. break Statement:

C#
for (int i = 0; i < 10; i++)
{
 if (i == 5)
 {
 Console.WriteLine("Reached number 5, exiting loop.");
 break;
 }
 Console.WriteLine(i);
}

2. continue Statement:

C#
for (int i = 0; i < 10; i++)
{
 if (i % 2 == 0) // Skip even numbers
 {
 continue;
 }
 Console.WriteLine(i);
}

Key Points:

When to Use break and continue:

By effectively using break and continue statements, you can create more flexible and controlled loops in your C# programs.

1. Finding the First Prime Number in an Array:

This example demonstrates using break to exit the loop as soon as a prime number is found:

C#
int[] numbers = { 10, 13, 15, 17, 20 };
for (int i = 0; i < numbers.Length; i++)
{
 int num = numbers[i]; // Current number
 bool isPrime = true; // Assume prime initially
 // Check divisibility by 2 (special case)
 if (num % 2 == 0 && num > 2)
 {
 isPrime = false;
 break; // Exit loop if divisible by 2 (except 2)
 }
 // Check for divisibility by odd numbers up to the square root
 for (int j = 3; j * j <= num; j += 2)
 {
 if (num % j == 0)
 {
 isPrime = false;
 break; // Exit inner loop and main loop if not prime
 }
 }
 if (isPrime)
 {
 Console.WriteLine("The first prime number is: {0}", num);
 break; // Exit the main loop once a prime is found
 }
}

2. Skipping Negative Numbers in a List:

This example uses continue to skip negative numbers in a List and only process positive ones:

C#
List numbers = new List() { -2, 5, 10, -3, 8 };
foreach (int number in numbers)
{
 if (number < 0)
 {
 continue; // Skip negative numbers
 }
 Console.WriteLine("Positive number: {0}", number);
}

3. Limiting Iterations in a for Loop:

This example demonstrates using break to limit the number of iterations in a for loop:

C#
for (int i = 0; i < 10; i++)
{
 Console.WriteLine("Iteration: {0}", i);
 if (i == 5)
 {
 Console.WriteLine("Reached iteration 5, stopping loop.");
 break;
 }
}

End of Outcome Quiz

1 of 20

    Quiz Score

    Percentage: 0%

    Answered Questions: 0

    Correct Answers: 0

    Faults: