C# – Introduction to Exceptions

Introduction: While compiling and executing the code, chance of getting different types of errors.

  • Compile time errors: Compiler raises error when we are not following language rules to develop the code.
    • Every Method should have return type.
    • Statement ends with semi-colon;
    • Invoking variable when it is not present

Logical Errors: If we get the output of code instead of Expected contains Logical error.

Expected			Result
1				12345
12				1234
123				123
1234				12
12345				1
  • Runtime Errors: Runtime Error is called Exception which terminates the normal flow of program execution.
    • Handling invalid input by user
    • Opening a file which is not present.
    • Connect to database with invalid user name and password.

FormatException: It occurs if user enter invalid input while reading through ReadLine().

using System;					
public class Program
{
	public static void Main(string[] args)
	{
		Console.WriteLine("Enter 2 integers to add : ");
		int a = Convert.ToInt32(Console.ReadLine());
		int b = Convert.ToInt32(Console.ReadLine());
		int c = a+b;
		Console.WriteLine("Result = " + c);
	}
}

Output:

Enter 2 integers to add :
10
abc
System.FormatException: Input string was not in a correct format
Scroll to Top