Most of code bases that you might have come across have some sort of error in them. Often the error messages are also not clear to fix it . This is where Exceptional handling is required.
Till now we have seen that if Python see's an error in the code then it stops executing the code after the point of error , However , Exceptional handling also allows users to continue running the script even after getting an error.
An error is handled using a try and except block. Often an else statement is also added to the block. The flow of logic through this block is explained below.
The try statement contains the code that is to be executed and if while executing the code there is an error , then the code block within the except statement is executed , however , if there is no error in the try statement then the code within the else statment is executed. Let us take an example on this.
In the the code below , i have a function that returns the sum of two numbers but if there is some sort of type error ( like giving a number in form of a string ) then it should also return the message ' hey! try giving numbers to the function instead of string '.
def func(n1,n2):
try:
return n1+n2
except:
return('hey! try giving numbers to the function instead of string ')
print(func(1,2))
print(func(1,'2'))
3
hey! try giving numbers to the function instead of string
Let us see an example using the else statement. In the code given below , i have a function that checks for an integer and as soon as it gets an integer it prints the number and breaks from the function. Note that the function keeps on taking input as long as it does not get an integer.
def check_int():
while True:
try:
number = int(input("enter the number : "))
except:
print("try entering a number instead of word" )
else:
print(number)
break
check_int()
not_a_number
5
enter the number : not_a_number
try entering a number instead of word
enter the number : 5
5
The keyword 'finally' can also be added to the try and except block and the block of code within 'finally' statement gets executed all the times . It does not depend upon the try statement.
Let us understand this with help of an example.
def func(n1,n2):
try:
print(n1+n2)
except:
print("try entering a number")
finally:
print("try and except block completed")
func(1,2)
func(1,'2')
3
try and except block completed
try entering a number
try and except block completed
The table below lists some of the very important and frequently occured exceptions in python along with the condition in which they might occur.
Exception | Description |
---|---|
AssertionError | Raised when the assert statement fails. |
AttributeError | Raised on the attribute assignment or reference fails. |
EOFError | Raised when the input() function hits the end-of-file condition. |
FloatingPointError | Raised when a floating point operation fails. |
GeneratorExit | Raised 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 (Ctrl+c or delete). |
MemoryError | Raised when an operation runs out of memory. |
NameError | Raised when a variable is not found in the local or global scope. |
NotImplementedError | Raised by abstract methods. |
OSError | Raised when a system operation causes a 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 the next() function to indicate that there is no further item to be returned by the iterator. |
SyntaxError | Raised by the parser when a syntax error is encountered. |
IndentationError | Raised when there is an incorrect indentation. |
TabError | Raised when the indentation consists of inconsistent tabs and spaces. |
SystemError | Raised when the interpreter detects internal error. |
SystemExit | Raised by the sys.exit() function. |
TypeError | Raised when a function or operation is applied to an object of an 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 translation. |
ValueError | Raised when a function gets an argument of correct type but improper value. |
ZeroDivisionError | Raised when the second operand of a division or module operation is zero. |
Let us go ahead and handle some common exceptions. In the code below , we will be handling IndexError.
# handling IndexError
mylist = [1,2,3,4]
for x in range(6):
try:
print(mylist[x])
except IndexError:
print("{} is not a valid index".format(x))
1
2
3
4
4 is not a valid index
5 is not a valid index
In the above code , we only had one error type and therefore there was no need to handle error 'specifically'. However , when there are multiple error types in a code and we want to handle different errors differently then we have to handle them separately using multiple except blocks. In the example below , we will be handling TypeError and ZeroDivisionError .
mylist = [1,2,3,4,'b']
for x in range(len(mylist)):
try:
print(mylist[x]/x) #dividing element in x by their index
except ZeroDivisionError:
print("division by zero is not possible")
except TypeError:
print("division operation cannot be performed on a character")
division by zero is not possible
2.0
1.5
1.3333333333333333
division operation cannot be performed on a character