19: Error Handling
Error Handling
A software is a mathematical machine and it should produce correct results and if there is some glitch in the program that makes the program unable to produce a proper result, it should end modestly. We can face three kinds of errors.
Syntax Errors
- This is the easiest error to remove.
- VS code and other modern code editors are very sharp and they just find this type of errors during program writing.
- These errors occur when we do not follow any rule of a given programming language.
- If we violate some rule then code editor, indicate it with a line under it.
- There can be multiple reasons for generating this kind of error.
Figure 1: Syntax Errors in Python
- When a code editor captures some syntax error then normally, it marks it with underline.
- On line 1 we assign a variable my_variable to another variable a but it is showing an error on my_variable.
- In fact, we did not create this variable and according to rule, we cannot assign the value of an unknown variable.
- On line 2, we can see that the string is faulty and a red line appears underneath.
- We did not use the closing quote for the string.
- In the third line, we use if as a variable while this is a keyword.
- As your experience in programming increases, the frequency of syntax error reduces.
- For newbies, there are some tips to identify syntax errors.
- If there is a syntax error, carefully read the error statement.
- Always check the spellings of variables and functions.
- Ensure that the variable and function is already created.
- Ensure starting and closing of quotes, parenthesis, braces and brackets.
- Keep focus on indentation in code blocking such as if, while, for and others.
- Ensure that for a function call that number of arguments are provided or not.
Logical Errors
- Logical errors can never be caught by the editor.
- Logical errors will not appear during program writing.
- The 6th step of program writing (testing) belongs to these errors.
- The testing phase starts just after completing the code, here the programmer provides some testing data and sees the output is OK.
- For example, you had written a program in addition to two numbers.
- Accidently, the subtraction symbol was used instead of addition.
- Now the program will run correctly without showing any error but when entering the data for testing, you will find an incorrect result.
- For instance, you entered 3 and 7 and the answer should be 7 but you will see the answer -1 which is incorrect. This is a logical error.
- Now this is the programmer’s responsibility to identify the mistake.
- In large programs, the probability of logical errors increased.
- Though the editors are unable to identify the logical mistakes in a program, they have a tool that can help to trace these.
- This tool is called Debugger. Fortunately, the debugger was installed with the Python extension.
- Consider the following example. We have to write a program that finds the sum of all numbers between 1 and 5.
num = 1total = 0while num < 5:  total = total + num  num = num + 1print (total)
Code 1: Incorrect Code for Calculating Sum
- When you run this code, the answer will be 10 which is incorrect. The sum of numbers between 1 to 5 is 15. This is a logical error.
- Use debugger to find the logical error following steps.
- Add a break point in code. Just hover on the line number in code. A small red dot appears. Click on it.
Figure 2: Breakpoint at Line 3
- Open the “Run” menu and select “Start Debugging”. Or press “F5”.
Figure 3: Running Program in Debug Mode
- It may take moments but you program will not run as usual due to debugging mode.
- If you select “Run without Debugging” then it will run conventionally.
Figure 4: Debug Toolbar (Blue) and Hitting Breakpoint (Red)
Figure 5: Description of Debug Toolbar
- When you click on the step over icon you will see that the pale background of line 3 moves to line 4.
- It means that line 3 executed and the condition given on line 3 is True, so it loaded line 4 into CPU for next processing.
- Here we again click on step over and it adds the value of num (which 1 at this time) in total (which is 0) and again save the value of to total and it becomes 1.
- You can also confirm the values by hovering the mouse on the values.
- After line 4, the line 5 will load and again click step over (or pressing “F10”), the value of num will be increased by 1.
- Line 5 is the last line inside the loop.
- After execution of line 5, the debugger again will load line 3 because it contains the whole statement and there is a condition that must be evaluated.
- You will also observe that the values in variables num and total also changed.
- The num variable contains 2 and total contains 1.
Figure 6: Looking Updated Value of num in 2nd Iteration of Loop
- By pressing F10 or clicking on the step over icon we continue loading and executing the statements. After executing line 5, the control jumps to line 3 again to evaluate the condition and it will find the condition is still True, so it again jumps into the loop body.
- For finding the logical error we should keep eye on variable values in each iteration.
- Before 1st iteration, values of num and total should be 1 and 0 respectively, before 2nd these values should be 2 and 1, before 3rd, these values will be 3 and 3 and for the 4th iteration these values will be 4 and 6.
- After the 4th iteration, these values will be 5 and 10 but when we evaluate the condition, it will be False because 5 is not less than 5 and it will not jump into the loop body for adding 5 into total which value is 10.
- Now we realize that condition has an issue. It is not valid for 5th iteration and missing the last addition in total and producing incorrect results.
- To enable it for the 5th iteration, we will change the condition to “while num <= 5:”.
Exceptions (Run Time Errors)
- Now our loop will execute one more time and produce the correct result.
- Exceptions are such errors which cannot be controlled by the developer.
- It is possible that the written code run without error but the same code causes a crash some other time.
- Consider the following code. We have to write a program that finds the quotient of two numbers.
numerator = int (input ("Enter a Numerator"))denominator = int (input ("Enter a Denominator"))answer = numerator / denominatorprint (answer)
Code 2:Â Simple Division Program. It may Cause of Crash
- This code is fine and has no syntax and logical error.
- Run this code and test it for (4, 2), (7, 3) and (100, 4). It will work and produce correct results.
- Now test this code for (8, 0) and you will find the following output.
Figure 7: Crash Error after Providing 0 as Denominator
- This is an error but the error message is long and a little bit confusing.
- We can see that the program works correctly with some values but the same program causes errors with some other values.
- We cannot anticipate or predict such errors.
- To avoid unexpected errors, we use try-except.
- The part of code that is suspected to produce errors during execution should be placed in the try block.
- The except block awakens when some error occurs. It will not execute on normal execution.
try:  numerator = int (input ("Enter a Numerator: "))  denominator = int (input ("Enter a Denominator: "))  answer = numerator / denominator  print (answer)except:  print ("Divide by Zero is not possible")
Code 3: Using try-except Block to avoid Crash
- The new code will run good for valid values and also run for denominator value 0.
- On error you will find the following output.
Figure 8: Error Message without Crash








