While, we write great codes in Python, we are bound to encounter some errors along the way. These errors that we can encounter in Python are generally of two types : one is the Syntax Errors and the other is the Exceptions. So, what basically is an Error? An error is a problem encountered in the program which makes it unable to thus, execute. Okay, Now what are Exceptions? Exceptions generally get raised where there is an internal error which causes or disrupts the normal flow and execution of the program. In this post, thus we will see one method to handle exceptions, i.e. The method of Try and Except in Python.

The Different Exceptions Types

Sr.No.Exception Name —>  Description
1Exception  —> It is the base class for all exceptions
2SystemExit  —> It gets raised due to the function sys.exit() .
3ZeroDivisionError —> It gets raised as and when division by zero takes place for all numeric types.
4AssertionError —> It gets raised when the Assert statement fails.
5EOFError —> It gets raised, in case of absence of input from input() or raw_input() function and also the end of file has been reached.
6IndexError —> It gets raised when an index is unavailable in a pattern.
7KeyError —> It gets raised when any specified key is not located in the dictionary.
8NameError —> Raises due to an identifier not being found in the local or global namespace.
9IOError —> Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
10SyntaxError —> Raised when there is an error in Python syntax.
11IndentationError —> Raised when indentation is not specified properly.
12TypeError —> Raised when an operation or function is attempted that is invalid for the specified data type.
13ValueError —> Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
14RuntimeError —> Raised when a generated error does not fall into any category.

Note : For vast knowledge, refer Python Catch All Exceptions

Try and Except in Python

The Try and Except methods in Python generally handle errors and exceptions of the sort mentioned above. This method has two parts : The Try block and the Except block. So, what does the Try block do? It checks for errors or also exceptions in your programming code. So, as to say that the code in the try block will only execute when the code does not encounter any error in the program. And. the code in the Except block executes whenever there is an error in your code and which has been encountered in the try block.
 Syntax: 

try:
    # Some block of Code
except:
    # block of code to execute when error encountered in the try block

Working of the try() block  
 

  • The code in the try block executes, on the condition that there is no exception encountered. If so, the except block does not execute.
  • But, in case there is any exception, the try block does not execute while the except block executes.
  • A try block can have more than one except block/clause.

Case 1: try() block of code runs because no exception is found.

# To show only the try() block of code runs as no exception is found.
def divide(a, b) :
        try :   
             ans = a // b 
             print("The resulting answer is  : ", ans)
      except ZeroDivisionError : 
             print("Sorry ! Division by zero is not possible ") 

Output : 
 

The resulting answer is : 1

Case 2: Only except clause is executed

# To show only the except() block of code runs as no exception is found.
def divide(a, b) :
        try :   
             ans = a // b
             print("The resulting answer is  : ", ans)
      except ZeroDivisionError : 
             print("Sorry ! Division by zero is not possible ") 

Output : 
 

Sorry ! Division by zero is not possible

The Else Block

The else block is used when the try block does not raise an exception. It is generally used after the try-except clauses.

Syntax:

try:
data = something_that_can_go_wrong

except IOError: 
handle_the_exception_error

else:
doing_different_exception_handling
# Program to depict else clause with try-except # Function which returns a/b
def div(x , y):
        try: 
              c = ((x + y) / (x - y))
       except ZeroDivisionError:
             print "x / y results in zero (0) "
       else:
             print c  

# Driver program to test above function 
div(4.0, 5.0)  
div(2.0, 2.0)

Output:

-9.0
x/y results in zero (0)

Finally Keyword in Python

Python provides a keyword finally, which is always executed after try and except blocks. The final block always executes after normal termination of try block or after try block terminates due to some exceptions.
 

Syntax:

try:
     # Some block of Code
except:
     # block of code to execute when error encountered in the try block
else:
    # executes when there is no exceptions
finally:
    # Some block of code   to execute always
  • It is optional.
  • Generally intended to define the clean-up actions which are to execute in any situation.
  • It usually executes before exiting the try statement, if or not an exception has been found.
  • Also, if no exception type is specified on the except line, the program catches all exceptions. So, handle with care.
try:
raise KeyboardInterrupt

finally:
print ‘Bye Bye, S P....’
Bye Bye, S P ...
KeyboardInterrupt
 Python catch all Exception
# finally() block of code execution
try :
      k = 5//0                    # raises divide by zero exception.
      print(k)    
except ZeroDivisionError :                    # handles the ZeroDivisionError exception 
      print("Not possible to divide by zero (0) ") 
finally :                            # the block which  is always executed
      print("Always  executes")

Output:

Not possible to divide by zero (0)
Always  executes

CONCLUSION

Through this article, thus, I have tried my best to make you aware of the different exceptions and errors in a Python program. Also, how to handle these errors using the method of Try and Except in Python. It is hereby, clear about the try() block, the except(), the else() block and the finally() block. In case, there are any doubts you can raise them in the comments to get it answered. Though, don’t worry there isn’t the try and except method used in the comments sections.

Categorized in: