

What is Error?
Simple Answer: An error is an action which is inaccurate or incorrect. In some usages, an error is synonymous with a mistake.Likewise, In statistics, “error” refers to the difference between the value which has been computed and the correct value. An error could result in failure or in a deviation from the intended performance or behaviour. Now come back to our programming language.The programmer should know the fact that there is very less chances that a program will run perfectly in first time. So the programmer has to make efforts to detect and rectify any kind of errors that are present in the
program. But before detecting and removing errors it is much more necessary
that the programmer should know about the types of errors in programming.
We can make certain mistakes while writing a program that lead to errors when we try to run it. These errors can be broadly classified into two classes:
- Syntax errors: Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error.The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage. Such an error is called a syntax error. The Python interpreter immediately reports it, usually along with the reason. Ex:
print “hello”
SyntaxError: Missing parentheses in call to ‘print’. Did you mean print(“hello”)?
2. Logical errors (Exceptions): Errors detected during execution are called exceptions or logical errors.Ex:
print( 0 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Let’s see some common error types:
- AssertionError: exception raise when an assert statement fails.Ex:
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
Output Will Be:
Average of mark2: 78.0
AssertionError: List is empty.
2. Attribute Error: Attribute errors in Python are generally raised when an invalid attribute reference is made.Ex:
a = 78
# Raises an AttributeError
a.append(98)
Output:
Traceback (most recent call last):
File "/aarti/pythonPrograms.py", line 3, in
X.append(98)
AttributeError: 'int' object has no attribute 'append'
3. EOFError: when the input() function hits an end-of-file condition.Call open(file,mode) with “r” as mode to open file for reading. Call file.read() to read the contents of file. If file.read() returns an empty str, it is the EOF.
open_file = open("file.txt", "r")
text = open_file.read()
eof = open_file.read()print(text)
Output:
print("End of File returns nothing",eof)
hello World #File content
End of File returns: # returns empty string
4. FileNotFoundError: when a file or directory is requested but doesn’t exist.Ex:
open_file = open("file.txt", "r")
text = open_file.read()
eof = open_file.read()print(text)
print(eof)
Output will be as “file.txt” doexn’t exists in my system:
Traceback (most recent call last):
File “C:UsersAartiPycharmProjectspythonProjecterrors.py”, line 1, in <module>
open_file = open(“file.txt”, “r”)
FileNotFoundError: [Errno 2] No such file or directory: ‘file.txt’
5. GeneratorExit: exception is raised when a generator or coroutine is closed.Generators in Python look like functions, but there is both a syntactic and a semantic difference. One distinguishing characteristic is the yield statements. The yield statement turns a functions into a generator. A generator is a function which returns a generator object. This generator object can be seen like a function which produces a sequence of results instead of a single object. This sequence of values is produced by iterating over it, e.g. with a for loop.
def generator():
try:
yield 1
print 1
except GeneratorExit:
print ‘Generator Exit’ g = generator()
print g.next()
g.close()
6. ImportError: when the import statement has troubles trying to load a module. Also raised when from is used to import any module, that cannot be found.Ex:
from toolkit.interface import interfaceOutput:
Traceback (most recent call last):
File "myCode.py", line 2, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
7. ModuleNotFoundError: A subclass of ImportError which is raised by import when a module could not be located. Ex:
import PrettyTable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'PrettyTable'
8. IndexError: raise when you try to index a string with an invalid index. Ex:
a = "Hello, World"
a[456]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a[456]
IndexError: string index out of range
9.KeyError: raised when you try to access the value of a key that doesn’t exist in a dictionary. Ex:
students = {"Mihir": 15, "Maya": 30}
students["John"]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
students["John"]
KeyError: 'John'
10. KeyboardInterrupt: raised when the user hits the interrupt key (normally Control-C or Delete).
11.MemoryError: generally occurs when the interpreter runs out of the memory.
a = []
i = "1"
while True:
a.append(i)
i += "1"*10000000000000Output:
Traceback (most recent call last):
File “C:UsersAartiPycharmProjectspythonProjecterrors.py”, line 11, in <module>
i += “1”*10000000000000
MemoryError
12.NameError: You will encounter a nameerror ( name is not defined) when a variable is not defined in the local or global scope. Or you used a function that wasn’t defined anywhere in your program.Ex:
number = 2
print(num)Output:Traceback (most recent call last):
File line 4, in <module> print(num)
NameError: name ‘num’ is not defined
13.NotImplementedError: Raised by abstract methods.User-defined base classes can raise NotImplementedError to indicate that a method or behavior needs to be defined by a subclass, simulating an interface.Ex:
import sys
try:
class Super(object):
@property
def example(self):
raise NotImplementedError("Subclasses should implement this!")
s = Super()
print (s.example)
except Exception as e:
print (e)
print (sys.exc_type)Output:
Subclasses should implement this!
Traceback (most recent call last):
raise NotImplementedError(“Subclasses should implement this!”)
NotImplementedError: Subclasses should implement this!
Common Exceptions:
AssertionError
Raised when an assert statement fails.
AttributeError
Raised when attribute assignment or reference fails.
EOFError
Raised when the input() function hits end-of-file condition.
FloatingPointError
Raised when a floating point operation fails.
GeneratorExit
Raise when a generator’s close() method is called.
ImportError
Raised when the imported module is not found.
IndexError
Raised when the index of a sequence is out of range.
KeyError
Raised when a key is not found in a dictionary.
KeyboardInterrupt
Raised when the user hits the interrupt key.
MemoryError
Raised when an operation runs out of memory.
NameError
Raised when a variable is not found in local or global scope.
NotImplementedError
Raised by abstract methods.
OSError
Raised when system operation causes system related error.
OverflowError
Raised when the result of an arithmetic operation is too large to be represented.
ReferenceError
Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError
Raised when an error does not fall under any other category.
StopIteration
Raised by next() function to indicate that there is no further item to be returned by iterator.
SyntaxError
Raised by parser when syntax error is encountered.
IndentationError
Raised when there is incorrect indentation.
TabError
Raised when indentation consists of inconsistent tabs and spaces.
SystemError
Raised when interpreter detects internal error.
SystemExit
Raised by sys.exit() function.
TypeError
Raised when a function or operation is applied to an object of incorrect type.
UnboundLocalError
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError
Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError
Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError
Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError
Raised when a Unicode-related error occurs during translating.
ValueError
Raised when a function gets an argument of correct type but improper value.
ZeroDivisionError
Raised when the second operand of division or modulo operation is zero.
To read more about exceptions:https://docs.python.org/3/library/exceptions.html
Thanks for giving your valuable time.