In C#, the terms Error and Exception are related but not the same - they describe different levels of problems that can occur in a program.
An Error is a serious issue that usually occurs outside the control of the program and cannot be handled by normal code execution.
Characteristics
Examples of errors
Example
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
try
{
List<byte[]> memoryHog = new List<byte[]>();
while (true)
{
memoryHog.Add(new byte[1024 * 1024 * 10]); // allocate 10MB repeatedly
}
}
catch (OutOfMemoryException ex)
{
Console.WriteLine("Error: " + ex.Message); //Error: Exception of type 'System.OutOfMemoryException' was thrown.
}
}
}
An Exception is an unexpected event that occurs during program execution, but can be handled using try-catch blocks.
Characteristics
Examples of Exceptions
Example
try
{
int x = 10;
int y = 0;
int result = x / y; // DivideByZeroException
}
catch (DivideByZeroException ex)
{
Console.WriteLine("You cannot divide by zero!");
}
| S.No. | Error | Exception | ||
|---|---|---|---|---|
| 1 | Serious system issue | Logical/runtime issue | ||
| 2 | No Recoverable | Recoverable | ||
| 3 |
|
|
||
| 4 |
|
Handled by try-catch - Yes | ||
| 5 | Example - StackOverflowException, OutOfMemoryException | Example - NullReferenceException, DivideByZeroException |