Exception Types
Part of the Logic & Flow section of Coddy's C# journey — lesson 24 of 66.
In C#, exceptions are categorized into different types based on the error they represent. Understanding these types helps you handle errors more effectively.
Let's look at the common exception types:
The base class for all exceptions is System.Exception.
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Handle any exception
Console.WriteLine(ex.Message);
}Some common exception types:
ArgumentException: Thrown when a method is called with an invalid argument.
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException: Thrown when you try to access a member on a null reference.
string text = null;
// This will throw NullReferenceException
int length = text.Length;IndexOutOfRangeException: Thrown when an array index is outside the bounds of the array.
int[] numbers = { 1, 2, 3 };
// This will throw IndexOutOfRangeException
int value = numbers[5];DivideByZeroException: Thrown when dividing an integer by zero.
int result = 10 / 0; // This will throw DivideByZeroExceptionYou can catch specific exceptions:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}Challenge
EasyCreate a method named ProcessArray that:
- Takes an array of integers and an index as parameters
- Tries to access the element at the specified index
- Returns the element value if successful
- If an
IndexOutOfRangeExceptionoccurs, catch it and return -1
Your method should have this signature:
public static int ProcessArray(int[] array, int index)Cheat sheet
The base class for all exceptions is System.Exception:
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Handle any exception
Console.WriteLine(ex.Message);
}Common exception types:
ArgumentException: Thrown when a method is called with an invalid argument:
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException: Thrown when accessing a member on a null reference:
string text = null;
int length = text.Length; // Throws NullReferenceExceptionIndexOutOfRangeException: Thrown when array index is outside bounds:
int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // Throws IndexOutOfRangeExceptionDivideByZeroException: Thrown when dividing an integer by zero:
int result = 10 / 0; // Throws DivideByZeroExceptionCatching specific exceptions:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}Try it yourself
using System;
class Program
{
public static int ProcessArray(int[] array, int index)
{
// Write your code here
return 0;
}
static void Main(string[] args)
{
// Read array input
string input = Console.ReadLine();
// Remove brackets if present
if (input.StartsWith("[") && input.EndsWith("]"))
{
input = input.Substring(1, input.Length - 2);
}
string[] parts = input.Split(',');
int[] array = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
array[i] = int.Parse(parts[i].Trim());
}
// Read index input
int index = int.Parse(Console.ReadLine());
int result = ProcessArray(array, index);
Console.WriteLine(result);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety