Uncategorized

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

  1. This is the easiest error to remove.
  2. VS code and other modern code editors are very sharp and they just find this type of errors during program writing.
  3. These errors occur when we do not follow any rule of a given programming language.
  4. If we violate some rule then code editor, indicate it with a line under it.
  5. There can be multiple reasons for generating this kind of error.

Figure 1: Syntax Errors in Python

  1. When a code editor captures some syntax error then normally, it marks it with underline.
  2. On line 1 we assign a variable my_variable to another variable a but it is showing an error on my_variable.
  3. In fact, we did not create this variable and according to rule, we cannot assign the value of an unknown variable.
  4. On line 2, we can see that the string is faulty and a red line appears underneath.
  5. We did not use the closing quote for the string.
  6. In the third line, we use if as a variable while this is a keyword.
  7. As your experience in programming increases, the frequency of syntax error reduces.
  8. For newbies, there are some tips to identify syntax errors.
  9. If there is a syntax error, carefully read the error statement.
  10. Always check the spellings of variables and functions.
  11. Ensure that the variable and function is already created.
  12. Ensure starting and closing of quotes, parenthesis, braces and brackets.
  13. Keep focus on indentation in code blocking such as if, while, for and others.
  14. Ensure that for a function call that number of arguments are provided or not.

Logical Errors

  1. Logical errors can never be caught by the editor.
  2. Logical errors will not appear during program writing.
  3. The 6th step of program writing (testing) belongs to these errors.
  4. The testing phase starts just after completing the code, here the programmer provides some testing data and sees the output is OK.
  5. For example, you had written a program in addition to two numbers.
  6. Accidently, the subtraction symbol was used instead of addition.
  7. Now the program will run correctly without showing any error but when entering the data for testing, you will find an incorrect result.
  8. 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.
  9. Now this is the programmer’s responsibility to identify the mistake.
  10. In large programs, the probability of logical errors increased.
  11. Though the editors are unable to identify the logical mistakes in a program, they have a tool that can help to trace these.
  12. This tool is called Debugger. Fortunately, the debugger was installed with the Python extension.
  13. 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

  1. 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.
  2. Use debugger to find the logical error following steps.
  3. 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

  1. Open the “Run” menu and select “Start Debugging”. Or press “F5”.

Figure 3: Running Program in Debug Mode

  1. It may take moments but you program will not run as usual due to debugging mode.
  2. 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

  1. When you click on the step over icon you will see that the pale background of line 3 moves to line 4.
  2. 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.
  3. 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.
  4. You can also confirm the values by hovering the mouse on the values.
  5. 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.
  6. Line 5 is the last line inside the loop.
  7. 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.
  8. You will also observe that the values in variables num and total also changed.
  9. The num variable contains 2 and total contains 1.

Figure 6: Looking Updated Value of num in 2nd Iteration of Loop

  1. 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.
  2. For finding the logical error we should keep eye on variable values in each iteration.
  3. 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.
  4. 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.
  5. 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.
  6. To enable it for the 5th iteration, we will change the condition to “while num <= 5:”.

Exceptions (Run Time Errors)

  1. Now our loop will execute one more time and produce the correct result.
  2. Exceptions are such errors which cannot be controlled by the developer.
  3. It is possible that the written code run without error but the same code causes a crash some other time.
  4. 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

  1. This code is fine and has no syntax and logical error.
  2. Run this code and test it for (4, 2), (7, 3) and (100, 4). It will work and produce correct results.
  3. Now test this code for (8, 0) and you will find the following output.

Figure 7: Crash Error after Providing 0 as Denominator

  1. This is an error but the error message is long and a little bit confusing.
  2. We can see that the program works correctly with some values but the same program causes errors with some other values.
  3. We cannot anticipate or predict such errors.
  4. To avoid unexpected errors, we use try-except.
  5. The part of code that is suspected to produce errors during execution should be placed in the try block.
  6. 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

  1. The new code will run good for valid values and also run for denominator value 0.
  2. On error you will find the following output.

Figure 8: Error Message without Crash

Leave a Reply

Your email address will not be published. Required fields are marked *