C# Exceptions
Exception Handling in C#
An exception is defined as an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of occurrence of an exception is not known to the program.
In such a case, we create an exception object and call the exception handler code. The execution of an exception handler so that the program code does not crash is called exception handling. Exception handling is important because it gracefully handles an unwanted event, an exception so that the program code still makes sense to the user.
Keyword | Definition |
| Used to define a try block. This block holds the code that may throw an exception. |
| Used to define a catch block. This block catches the exception thrown by the try block. |
| Used to define the finally block. This block holds the default code. |
| Used to throw an exception manually. |
Let us take a simple example to understand what an exception is:
Error
In the code given above, the array named arr
is defined for 5 elements, indices 0 to 4. When we try to access the 7th element of the array, that is non-existent, program code throws an exception and the above message is displayed.
The exception can be handled using the System.Exception
class of C#. This will be depicted in the code given below.
Exception Handling Using try-catch block
The code given below shows how we can handle exceptions using the try-catch block. The code that may generate an exception is placed inside the try block. In this case, the access to the 7th element is put inside the try block.
When that statement is executed, an exception is generated, which is caught by the catch block. The object of the type IndexOutOfRangeException
is used to display a message to the user about the exception that has occurred.
Syntax
Using Multiple try-catch blocks
In the code given below, we attempt to generate an exception in the try block and catch it in one of the multiple catch blocks. Multiple catch blocks are used when we are not sure about the exception type that may be generated, so we write different blocks to tackle any type of exception that is encountered.
The finally block is the part of the code that has to be executed irrespective of if the exception was generated or not. In the program given below the elements of the array are displayed in the finally block.
The finally
block is the part of the code that has to be executed always!
Syntax
Last updated