Why we need exception handling in programming

Imagine that you have written some code. The code should do what you have instructed it to, right? But for some reason the software is unable to execute the commands you have given. Maybe the software is facing some issues that make it impossible to run.

For example, let's say that you have instructed the software to read a file, collect data, and store it in a database. However, the software is unable to find the file at the location where the file is supposed to be. There could be many reasons why the file isn't found there: the file may have been deleted by someone or may have been moved to another location. Now, what will your software do? It's not smart enough to handle this situation automatically. If the software is not clear about its work, it will throw an exception. It is our duty as a software developer to tell the software what to do in these kind of situations.

The software will let us know that it is stuck and can't resolve the situation by passing a message. But what should it say to us? Help! Help! won't be an appropriate message, and this kind of message won't make the developer's life any easier. We need more information about the situation so that we can guide the computer to work accordingly. For that reason, the .NET framework has created some very common exceptions that occur very often in programming. If the problem that the software is facing has a predefined exception, it will throw that. For example, say that there is a program that is trying to divide a number by zero. Mathematically, this is not possible, but the computer has to do it because you have instructed it to do so. Now the computer is in big trouble; it's confused and helpless. It tries to divide the number by zero as you instructed, but then the compiler will stop it and say Ask for help, Mr. Program!, which means throw a DivideByZeroException to your master for help. The program will then throw a DivideByZeroException and expect some code that the programmer has written to handle it. This is how we will actually know what exceptions we need to handle in the program. This is why we need exceptions in programming.  

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.62.122