List 2 different types of errors in c#?

In C#, errors can be broadly classified into two main types:

1. Compile-time errors (or Compilation errors):

  • Compile-time errors occur during the compilation phase of the code. These errors are detected by the compiler when it attempts to translate the source code into an intermediate language (IL) or executable code.
  • Common causes of compile-time errors include syntax errors, type mismatches, missing references, and other issues that prevent the code from being successfully compiled into a runnable program.
  • Since compile-time errors prevent the program from being built, the code must be corrected before it can be executed.

Example of a compile-time error:

using System;

class Program
{
    static void Main()
    {
        // Syntax error: Missing closing parenthesis
        Console.WriteLine("Hello, World!";
    }
}

2. Runtime errors (or Execution errors):

  • Runtime errors occur during the execution phase of the code when the program is running. These errors are not detected by the compiler and may arise due to various reasons such as invalid input, unexpected data, or logical issues in the code.
  • Runtime errors are also known as exceptions because they are represented by instances of the 'System.Exception' class or its derived types. When an exception occurs and is not caught and handled, it may terminate the program abruptly.
  • Common types of runtime errors include 'DivideByZeroException', 'NullReferenceException', 'IndexOutOfRangeException', and custom exceptions created by developers.

Example of a runtime error:


using System;

class Program
{
    static void Main()
    {
        int a = 10;
        int b = 0;

        // Runtime error: Divide by zero
        int result = a / b;
        Console.WriteLine("Result: " + result);
    }
}

It's important to handle runtime errors gracefully using structured exception handling (try-catch-finally) to avoid program crashes and provide meaningful error messages to users. Additionally, writing clean and correct code helps prevent both compile-time and runtime errors, ensuring smoother program execution.