Types of Errors in Python
When coding programs there are three common types of errors that can occur. It is useful to recognize these different error types in Python programming so they can be corrected easily:
1. Syntax Error --
This Error occurs when the interpreter encounters code that does not conform to the Python language rules.
For example, a missing quote mark around a string. The interpreter halts and reports the error without executing the program.
Open IDLE and Edit Window then add a statement to output a string that omits a closing quote mark.
print('Coding for Beginners in easy steps)
Save and run the program to see the interpreter highlight the syntax error and indicate
Insert a quote mark before the closing parenthesis to terminate the string and save then run the program again - to see the error has been corrected.
2. Runtime Error --
This Error occurs during execution of the program, at the time when the program runs.
when a variable name is later mis-typed so the variable cannot be recognized. The interpreter runs the program but halts at the error and reports the nature of the error as an "Exception".
Ex: By initializing a variable, try to output its value with an incorrect variable name - to see the interpreter report a runtime error.
Amend the variable name to match that in the variable declaration and save then run the program again - to see the error has been corrected.
SOME RUN TIME ERRORS ARE:
1.Divisible By Zero Error:
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
2. Type Error:
>>>len(42) # this causes a TypeError, because a number is the wrong type for the function
3. Value Error:
>>>int("dog") # this causes a ValueError, because "dog" cannot be converted to an int value
4. Index Error:
my_list = [3,7, 9, 4, 6]
except IndexError as e:
list index out of range
3. Semantic Error --
This Error occurs when the program performs unexpectedly.
Forexample, when order precedence has not been specified in an expression. The interpreter runs the program and does not report an error.
Ex: By initializing a variable, try to output an expression using its value without explicit precedence - to see a possibly unexpected result of 28.
Add parentheses to group the expression as 3*(8+4) then save the file and run
the program again - to see the expected result of 36, correcting the semantic error.
NOTE: Correcting Syntax and Runtime errors is fairly straightforward, as the
interpreter reports where the error occurred or the nature of the error type, but
semantic errors require code examination.