C# - Difference Between Error and Exception


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.

Error in C#

An Error is a serious issue that usually occurs outside the control of the program and cannot be handled by normal code execution.

Characteristics

  1. Represents system-level issues.
  2. Usually caused by external conditions or serious faults (like memory corruption, stack overflow, or hardware failure).
  3. The program cannot recover from an error.
  4. Commonly indicates a problem with the environment or runtime, not your code logic.

Examples of errors

  1. OutOfMemoryException
  2. StackOverflowException
  3. AccessViolationException
  4. ExecutionEngineException

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.
        }
    }
}

Exception in C#

An Exception is an unexpected event that occurs during program execution, but can be handled using try-catch blocks.

Characteristics

  1. Represents recoverable problems.
  2. Typically caused by logical or runtime issues in the application.
  3. Can be handled and recovered gracefully.
  4. You can create custom exceptions.

Examples of Exceptions

  1. NullReferenceException
  2. DivideByZeroException
  3. FileNotFoundException
  4. InvalidOperationException

Example

try
{
    int x = 10;
    int y = 0;
    int result = x / y; // DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("You cannot divide by zero!");
}

Difference between Error and Exception

S.No. Error Exception
1 Serious system issue Logical/runtime issue
2 No Recoverable Recoverable
3
Environment or runtime failure
Application code or invalid input
4
Handled by try-catch-Usually Not
Handled by try-catch - Yes
5 Example - StackOverflowException, OutOfMemoryException  Example - NullReferenceException, DivideByZeroException

Prev Next