An exception is an event that occurs during the execution of the program i.e. during run–time. This event is unexpected, not known by the program, and disrupts the normal flow of the code. So to handle such errors, we create an exception handler code which will be executed when it finds an exception in a program.
Exception handling is a mechanism to maintain the normal flow of a program by handling runtime errors. The main advantage of exception handling is to ensure that even when an exception occurs, the program’s flow doesn’t break.
C# Exception Classes
The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Let us go through some of the predefined exception classes derived from the Sytem.SystemException
.
Exception | Description |
---|---|
System.DivideByZeroException | It handles the error generated by dividing a number by zero. |
System.IndexOutOfRangeException | It handles the error when the array index is out of range. |
System.NullReferenceException | It handles the error generated by referencing the null object. |
System.ArrayTypeMismatchException | It handles the error of array mismatched type. |
System.InvalidCastException | It handles the error generated during typecasting. |
System.IO.IOException | It handles the Input-Output errors. |
System.OutOfMemoryException | It handles the insufficient free memory error. |
System.FieldAccessException | It handles the error generated by invalid private or protected field access. |
System.StackOverflowException | It handles the error generated during stack overflow. |
C# Exception Handling Keywords
C# provides four different keywords to handle the exception.
- try: The try block identifies the block of code for which the exception will be activated. It is followed by a catch block.
- catch: The catch indicates the cathching of an exception where you want to catch the error accuring in the program. It is placed right after the try block.
- finally: Finally block is used to execute the code followed by the try-catch block. finally block is always executed whether an exception is handled or not.
- throw: throw keyword is used to throw an exception when a problem shows up in a program.
C# try/catch and finally block
As discussed above, the try block contains the code that might throw an exception, catch handles an exception if there exists any, and finally block is used for any cleanup work that needs to be done. finally is always executed whether there exists an exception or not.
The syntax for a try, catch, and finally keyword.
1 2 3 4 5 6 7 8 9 10 11 12 | try { // exception causing block } catch(Type x) { // handling block } finally { //clean up block } |
Let us go through an example in C#.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; namespace ExceptionEg { public class Program { public static void Main(string[] args) { int x = 15; int y = 0; int result; try { result = x / y; } catch (Exception e) { Console.WriteLine(e); } finally { Console.WriteLine("Finally block is executed"); } } } } |
Output:
System.DivideByZeroException: Attempted to divide by zero.
at....
Finally block is executed
C# User-Defined Exceptions
C# allows us to create our own exception in order to make it more meaningful. User-defined exception classes are derived from the Exception class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | using System; class TestTemperature { static void Main(string[] args) { Age age = new Age(); try { age.validateAge(18); } catch (InvalidAgeException e) { Console.WriteLine("InvalidAgeException: {0}", e.Message); } } } public class InvalidAgeException: Exception { public InvalidAgeException(string message): base(message) {} } public class Age { public void validateAge(int age) { if (age < 21) { throw (new InvalidAgeException("Age must be greater than 21")); } else { Console.WriteLine("Age: " + age); } } } |
Output:
InvalidAgeException: Age must be greater than 21
Go through throw keyword in C# topic next.