-
Notifications
You must be signed in to change notification settings - Fork 5
Exception Handling
Exception handling in C# is a mechanism to handle runtime errors, ensuring the program can respond to unexpected conditions gracefully. The primary way to handle exceptions is through the use of
try
,catch
,finally
, andthrow
statements.
- try-catch Block
Surround code that might throw an exception with a
try
block, and handle exceptions with one or morecatch
blocks.
using System;
class Program
{
static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // This will throw an exception
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
- finally Block
The
finally
block contains code that is always executed, regardless of whether an exception is thrown or caught. It is typically used for cleanup code.
using System;
using System.IO;
class Program
{
static void Main()
{
StreamReader reader = null;
try
{
reader = new StreamReader("example.txt");
Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
if (reader != null)
{
reader.Close();
}
Console.WriteLine("Cleanup code executed.");
}
}
}
- throw Statement
Use the
throw
statement to explicitly throw an exception, either caught or newly created.
using System;
class Program
{
static void Main()
{
try
{
ValidateAge(15);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
}
}
static void ValidateAge(int age)
{
if (age < 18)
{
throw new ArgumentOutOfRangeException("Age must be 18 or older.");
}
}
}
- Custom Exceptions
Define your own exceptions by creating a class that inherits from
Exception
.
using System;
class Program
{
static void Main()
{
try
{
PerformOperation(0);
}
catch (CustomException ex)
{
Console.WriteLine($"Custom exception caught: {ex.Message}");
}
}
static void PerformOperation(int value)
{
if (value == 0)
{
throw new CustomException("Value cannot be zero.");
}
}
}
public class CustomException : Exception
{
public CustomException(string message) : base(message) { }
}
- try-catch: Handle exceptions where they occur.
- finally: Execute code regardless of exceptions, useful for cleanup.
- throw: Explicitly throw exceptions.
- Custom Exceptions: Create exceptions specific to application needs.
C# exception handling provides robust mechanisms to manage errors and maintain program stability, making it easier to develop reliable applications.
-
Introduction to C#
What is C#? -
Variables and Data Types
Understand how to declare and use variables. -
Operators
Arithmetic, relational, and logical operators in C#. -
Control Statements
If-else, switch, and looping constructs.
-
Classes and Objects
Basics of OOP in C#. -
Inheritance
How to use inheritance effectively. -
Polymorphism
Method overriding and overloading. -
Encapsulation
Understanding access modifiers.
-
LINQ Basics
Working with Language Integrated Query. -
Asynchronous Programming
Introduction to async/await. -
File Handling
Reading and writing files.
-
Number Formatting
Formatting numbers in C#. -
Exception Handling
Handling runtime errors effectively. -
Working with Dates
DateTime and time zone handling. -
Using Keyword in C#
Different usages of theusing
keyword in C#.
-
Setting Up Development Environment
Installing Visual Studio and .NET SDK. - Useful Libraries Libraries and tools for C# development.