Errors and Exceptions in Python
Errors are problems in a program that causes the program to stop its execution.
a) Syntax errors: errors due to when proper syntax of the language is not followed.
Eg:- if(amt>2000) // semicolon missing
Output: syntax error: invalid syntax
If(a<3) // indentation is not correct
Print(a)
Output: Indentation error:expected an indented block
b) Semantic errors: errors due to an improper use of program statements spelling
mistakes in keywords
Eg:- de add(): // def keyword
c) Logical errors: errors due to the fact that the specification is not followed.
Incorrect behaviour of output.
The average of the numbers [10, 20, 30, 40, 50] should be 30 .
Actual Output: The program will output The average is: 29.0 .
Characteristics of Logical Errors
No Syntax Error: The code runs successfully without any syntax errors.
Unexpected Output: The program produces output that is different from what
is expected.
Difficult to Detect: Logical errors are harder to identify and fix compared to
syntax errors because the program appears to run correctly.
Varied Causes: They can arise from incorrect assumptions, faulty logic,
improper use of operators, or incorrect sequence of instructions.
when errors are detected, we can distinguish:
1. Compile time errors: syntax errors and static semantic errors indicated by the
compiler.
2. Runtime errors: dynamic semantic errors, and logical errors, that cannot be detected
by the compiler (debugging).
Exceptions are raised when some internal events change the program’s normal flow.
Errors that occur at runtime (after passing the syntax test) are called exceptions or logical
errors.
For instance, they occur when we
try to open a file(for reading) that does not exist (FileNotFoundError)
try to divide a number by zero (ZeroDivisionError)
try to import a module that does not exist (ImportError) and so on.
divide_numbers = 7 / 0print(divide_numbers)
Output
Traceback (most recent call last):
File "<string>", line 1, in <module>
ZeroDivisionError: division by zero
Common Builtin Exceptions
Exception Description
IndexError When the wrong index of a list is retrieved.
AssertionError It occurs when the assert statement fails
AttributeError It occurs when an attribute assignment is failed.
ImportError It occurs when an imported module is not found.
KeyError It occurs when the key of the dictionary is not found.
NameError It occurs when the variable is not defined.
MemoryError It occurs when a program runs out of memory.
It occurs when a function and operation are applied in an incorrect
TypeError
type.
EOFError input() hits an end-of-file condition (EOF) without reading any data
when an operation or function is applied to an object of inappropriate
TypeError
type.