C# - Exceptions and Exception Handling

Dev_NarenDev_Naren
6 min read

In the development of an application, we will be coming across 2 different types of errors, like:

  1. Compile time errors.

  2. Runtime errors.

Errors which occur in a program while the execution of a program is taking place are known as runtime errors, which can occur due to various reasons like wrong implementation of logic, wrong input supplied to the program, missing of required resources etc. Runtime errors are dangerous because when they occur under the program, the program terminates abnormally at the same line where the error got occurred without executing the next lines of code. To test this ,add a new class naming it as ExceptionDemo.cs & write the following code.

Execute the above program by using Ctrl+F5, and here there are chances of getting few runtime errors under the program, to check them enter the value for y as ‘0’ or enter character input for x or y values, and in both cases when an error got occurred program gets terminated abnormal on the same line where error got occurred.

Exception : In C#, errors in the program at run time are caused through the program at run time are caused through the program by using a mechanism called Exceptions.Exceptions are classes derived from class Exception of System namespace. Exceptions can be thrown by the .NET Framework CLR(Common Language Runtime) when basic operations fail or by code in a program. Throwing an exception involves creating an instance of an Exception-derived class, and then throwing that instance by using the throw keyword. There are so many Exception classes under the Framework Class Library where each class is defined representing a different type of error that occurs under the program, for example FormatException, NullReferenceException, IndexOutOfRangeException, ArithmeticException etc.

Exceptions are basically 2 types like SystemExceptions and Application Exceptions. System Exceptions are pre-defined exceptions that are fatal errors which occur on some pre-defined error conditions like DivideByZero, FormatException, and NullReferenceException etc. ApplicationExceptions are non-fatal errors i.e. these are error that are only caused by the programs explicitly. Whatever the exception it is every class of class Exception only and the hierarchy of these exception classes will be as following:

[?]Exception

[?]SystemException

[?] FormatException

[?] NullReferenceException

[?] IndexOutOfRangeException

[?] ArithmeticException

[?] DivideByZeroException

[?] OverFlowException

[?]ApplicationException

Exception Handling : It is a process of stopping the abnormal termination of a program whenever a runtime error occurs under the program: if exceptions are handled under the program, we will be having the following benefits:

  1. As abnormal termination is stopped, statements that are not related with the error can be still executed.

  2. We can also take any corrective actions which can resolve the problems that may occur due to the errors.

  3. We can display user friendly error messages to end users in place of pre-defined error messages.

How to handle an Exception: to handle an exception we need to enclose the code of the program under some special blocks known as try and catch blocks which should be used as following:

try

{

-Statement’s where there is a chance of getting runtime errors.

-Statement’s which should not execute when the error occurs.

}

catch(<Exception Class Name>[<Variable>])

{

-Statement’s which should execute only when the error occurs.

}

[—-<multiple catch blocks if required>—-]

To test handling exceptions, add a new class TryCatchDemo.cs and following code:

If we enclose the code under, try and catch blocks the execution of program will take place as following:

  • If all the statements in the try block run successfully (i.e., no error in the program), the control jumps directly from the last statement of the try block to the first statement after all the catch blocks.

  • If any statement in the try block causes an error, the control jumps directly to the catch blocks, without executing any other lines of code in the try block, searching for a catch block to handle the error.

  • If a catch block is available that can handle the exception, the exception is caught by that catch block, executes the code inside that catch block, and then jumps to the first statement after all the catch blocks.

  • If a catch block is not available to handle the exception that occurred, abnormal termination occurs again at that line.

Note : Message is a property under the Exception class which gets the error message associated with the exception that got occurred under the program, this property was defined as virtual under the class Exception and overridden under all the child classes of Exception as per their requirement, that is reason why when we call ex.Message under the last catch block, even if “ex” is the reference of parent class, it will get the error message that is associated with the child exception class but not of itself because we have already learnt in overriding that “parent’s” reference which is created by using child classes instance will call classes overridden members “i.e.,nothing but dynamic polymorphism.

Finally Block : this is another block of code that can be paired with try along with catch or without catch also and the speciality of this block is, code written under this block gets executed at any cost. i.e., when an exception got occured only when there is no exception under the program and statements under catch block will be executed only when there is exception under the program whereas code under finally block gets executed in both the cases.

To test finally block add a new class “FinallyDemo.cs” and write the following code.

“Execute the above program for 2 times, first time by giving input which doesn’t cause any error and second time by giving the input which causes an error and check the output where in both the cases finally block is executed.

In both the cases not only finally block along with it “End of the program.” Statement also gets executed, now test the program for the third time by giving the divisor value i.e., value to y as 1, so that, the if condition in the try block gets satisfied and return statement gets executed. As we are aware that return is a jump statement which jumps out of the method in execution, but in this case, it will jump out only after executing the finally block of the method because once the control enters try, we cannot stop the execution of finally block.

Note : try,catch, and finally blocks can be used in 3 different combination like:

i . try and catch in this case exceptions that occur in the program are caught by the catch block so abnormal termination will not take place.

ii. try,catch & finally : In this case behavior will be same as above but along with it finally block keeps executing in any situation.

iii. try and finally : In this case exceptions that occur in the program are caught because there is no catch block so abnormal termination will take place but still the code under finally block gets executed.

Note : to test try & finally, comment the catch block in the previous program and execute the program again, now when there is any runtime error, exception occurres and program gets abnormally terminated but in this case also we see finally block getting executed.

In next blog we will see Application Exception.

0
Subscribe to my newsletter

Read articles from Dev_Naren directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dev_Naren
Dev_Naren

I am a software developer. Exploring tech world. I just post my thoughts about tech and anythings which I'm curious about.