0% found this document useful (0 votes)
8 views6 pages

C# Exception Handling Examples

The document provides multiple C# programming examples demonstrating exception handling techniques, including basic try-catch blocks for division and array access, custom exceptions for age validation, and exception handling in a Windows Forms application for adding two numbers. Each example includes code snippets, expected outputs, and error handling scenarios for invalid inputs. The document emphasizes the importance of managing exceptions to ensure robust and user-friendly applications.

Uploaded by

jasiaakram884
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

C# Exception Handling Examples

The document provides multiple C# programming examples demonstrating exception handling techniques, including basic try-catch blocks for division and array access, custom exceptions for age validation, and exception handling in a Windows Forms application for adding two numbers. Each example includes code snippets, expected outputs, and error handling scenarios for invalid inputs. The document emphasizes the importance of managing exceptions to ensure robust and user-friendly applications.

Uploaded by

jasiaakram884
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Basic Try-Catch Example

Q: Write a C# program that takes two integers as input from the user and
divides the first number by the second. Handle the case where the
denominator is zero using a try-catch block.
using System;

class Program
{
static void Main()
{
try
{
[Link]("Enter first number: ");
int num1 = Convert.ToInt32([Link]());

[Link]("Enter second number: ");


int num2 = Convert.ToInt32([Link]());

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


[Link]("Result: " + result);
}
catch (DivideByZeroException)
{
[Link]("Error: Cannot divide by zero!");
}
catch (FormatException)
{
[Link]("Error: Invalid input! Please enter integers.");
}
finally
{
[Link]("Execution completed.");
}
}
}

Output:
Enter first number: 10
Enter second number: 0

Error: Cannot divide by zero!


Execution completed.

2. Handling Multiple Exceptions


Q: Write a C# program that asks the user to enter an index number and
displays the corresponding element from an array. Handle exceptions for
invalid index and non-integer input.
using System;

class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };

try
{
[Link]("Enter an index: ");
int index = Convert.ToInt32([Link]());

[Link]("Value at index {0}: {1}", index, numbers[index]); // May cause


IndexOutOfRangeException
}
catch (IndexOutOfRangeException)
{
[Link]("Error: Index out of range! Enter a value between 0 and 4.");
}
catch (FormatException)
{
[Link]("Error: Invalid input! Please enter an integer.");
}
finally
{
[Link]("Program execution finished.");
}
}
}

Output:
Enter an index: 5
Error: Index out of range! Enter a value between 0 and 4.
Program execution finished.

3. Custom Exception Handling

Q: Create a C# program where a user enters their age. If the age is less than
18, throw a custom exception "UnderAgeException". Otherwise, display a success
message.
using System;
class UnderAgeException : Exception
{
public UnderAgeException(string message) : base(message) { }
}

class Program
{
static void Main()
{
try
{
[Link]("Enter your age: ");
int age = Convert.ToInt32([Link]());

if (age < 18)


throw new UnderAgeException("Error: Age must be 18 or above!");

[Link]("Access granted. You are eligible.");


}
catch (UnderAgeException ex)
{
[Link]([Link]);
}
catch (FormatException)
{
[Link]("Error: Invalid input! Please enter an integer.");
}
finally
{
[Link]("Process completed.");
}
}
}

Output 1:
Enter your age: 16
Error: Age must be 18 or above!
Process completed.

Output 2:
Enter your age: 22
Access granted. You are eligible.
Process completed.
Q: Windows Forms application Add Two numbers to input two numbers in text boxes and display
result in 3rd text box. Apply Exception handling on input.

using System;
using [Link];
namespace AddNumbersApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
// Read numbers from text boxes
int num1 = Convert.ToInt32([Link]);
int num2 = Convert.ToInt32([Link]);
// Compute sum
int sum = num1 + num2;
// Display result in third text box
[Link] = [Link]();
}
catch (FormatException)
{
[Link]("Error: Please enter valid numbers!");
}
catch (OverflowException)
{
[Link]("Error: Number too large!");
}
catch (Exception ex)
{
[Link]("Unexpected Error: " + [Link]);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Clear text fields
[Link]();
[Link]();
[Link]();
[Link]();
}
}
}
Output:

Expected Output Scenarios

✅ Valid Input:

• textBox1 = 10, textBox2 = 20


✔ textBox3 Output:

30

❌ Invalid Input (Non-Numeric):

• textBox1 = "abc", textBox2 = 5


🔴 MessageBox Output:

Error: Please enter valid numbers!


❌ Empty Input Field:

• textBox1 = "", textBox2 = "10"


🔴 MessageBox Output:

Error: Please enter valid numbers!

❌ Overflow Exception:

• textBox1 = 9999999999, textBox2 = 1


🟠 MessageBox Output:

Error: Number too large!

UI Design (Default Control Names)

Control Default Name Properties

Label label1 Text = "Enter First Number:"

TextBox textBox1 Input field for first number

Label label2 Text = "Enter Second Number:"

TextBox textBox2 Input field for second number

Button button1 Text = "Add Numbers"

Label label3 Text = "Result:"

TextBox textBox3 ReadOnly = true (Result display)

Button button2 Text = "Clear"

You might also like