Python Exception Handling and Basic Examples

Hello, readers welcome back to know the Python Exception Handling and Basic Examples. It is a continuation of the previous article which defines the importance of exception handling in real-time applications. There are many run time exceptions which are shown in the previous article.

Python Exception Handling undergoes with a try, except, and finally blocks. Will look in detail in the below sections.

Key Points of Python Exception Handling and Basic Examples:

Try Block:

It allows to write error occurrence code and error is captured and send to ‘except’ block. Most often we write the errorless programs, but sometimes we may not handle computer raised errors in the background. To know the exact errors with the definition we put the code in the try block. This is the importance of try block and we will discuss more below with the examples. please follow till the end.

Except Block:

To catch the error occurred in the try block is written in except block. In python, it is written with a keyword ‘except exception_type’. Please, you can follow the example which is written below. It handles the error which occurred in the try block and handles.

Finally Block:

It is used to execute the code which is written in spite of the result of try-except blocks. The code which we want to execute in spite of errors must be written in the ‘finally’ block or else an important block and closing connections etc.  Please, you can follow the example which is written below example for better understanding.

Identification of the points of failure:

There may be even more errors than those identified. However, from the found ones it is possible to determine the problematic code sections. In this case, the points of failure occur when invoking the function and also within the function. Errors that are generated when invoking the function can only be solved by re-entering the arguments correctly. However, errors that occur within the function can be managed.

Resources for capture and management of exceptions:

Python has a series of resources that allow the capture and management of exceptions. If the exception is not captured, it will run to its ultimate consequences: Send an error message and close the interpreter.

The management resources and exception capture are:

  • Try: It allows to write error occurrence code and error is captured and send to ‘except’ block
  • except: It handles the error which occurred in the try block and handles
  • else: It is used to print the message
  • finally: It is used to execute the code which is written in spite of the result of try-except blocks.

Delimitation of the code by means of try:

When a section of code susceptible to errors is identified, it can be delimited with the expression try. Any exception that occurs within this code section may be captured and managed.

Capture and manage the exceptions except:

The expression except is responsible for managing the exceptions that are captured. If except with more data, it will execute the code it contains for all the exceptions that occur.

Let us discuss the flow of an exception handling:

#main flow
    code block at risk
    inscribed block except
#/main flow

Let us try with some python exceptions and basic examples:

This new function is based on exception_probable () and delimits the block of code susceptible to errors. On this occasion, all the exceptions that are generated will be captured without taking any type of action.

>>> def  basic_exception(number):
	try :
		number  =  float(number)
		print( "The square root of the number % f is % f "  %  ( number ,  number  **  0.5 ))
>>> basic_exception(-1)
>>> basic_exception(13j)
>>> basic_exception("15")
The square root of the number  15.000000 is  3.872983 

Management of exceptions by its type:

The expression except can be used in such a way that it executes code depending on the type of error that occurs in a way very similar to elif. In this way, exceptions can be managed differently depending on the type of error that is generated.

#main flow
    code susceptible to error
except Error Type1:
    block inscribed to Error Type1
except Error Type2:
    block inscribed to Error Type2
except (Error Type3,  Error Type4)
    block inscribed to Error Type3 and Error Type4
    inscribed block except general
#/main flow

Capture of the error details:

It is possible to capture the message that Python displays by detailing an error by except binding it to a name using the following syntax:

except <type of error> as <name>:

The expression as:

There are some cases in which syntactically it is not possible to use the assignment operator (=) to bind a name to an object in the namespace. The expression as acts identically to the identity operator, but with a different syntactic structure as in the case of except to capture the description of the error.

Example of using ‘as’:

>>> def  Exceptions_described(number):
	occur_error  =  False
		number  =  float(number)
		print( " The square root of the number % f is % f "  %  ( number,  number  **  0.5 ))
	except TypeError as description:
		occur_error  =  True
		print( "An expected error occurred:" ,  description )
		occur_error  =  True
		print( "I do not know what happened!" )
	if  occur_error :
>>> Exceptions_described(-1)
An expected error occurred: can't convert complex to float

Use else and finally:

  • In addition to except, Python has two other resources that complete exception handling.

The expression else:

As with if, the else expression is executed in the case that an exception is not generated. The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

In the below-written example, we are opening a file named ‘BottlePython.txt’ and passing to the variable f and executing in the else block.

    f = open('BottlePython.txt','r')
except OSError:
    print('cannot open', 'BottlePython.txt')
    print('Bottle Python.txt', 'has', len(f.readlines()),'lines')

The expression finally:

In some situations, it is necessary to perform some operations regardless of whether an exception occurred or not. This is common when you have to close communication on the Internet, close the access to a database or close a file in write mode. For these situations, we use the expression finally, which is executed if there was an exception or not. using finally block you can identify python exception handling and basic examples in different combinations.

>>>import pymysql
    #database connections
    db_connection = pymysql.connect("localhost","root","root123","testddb")
    #checking database connections
    if db_connection:
        print(‘database connection has been established’)
except Exception as dbe:
    #catching the exception 
    print(‘Connection Error ’, dbe)
    #using finally block to close the connection once its finished.


Raising exceptions with raise:

On certain occasions, it is possible to identify a situation in which a certain condition will cause an error. In that case, an exception can be raised before the error occurs and issue a corresponding message.

The expression raise is used to raise exceptions defined by the programmer.

Here is an example to raise the exceptions with ‘raise’ keyword. Which undergoes python exception handling and basic examples tutorial guide.

>>> try:
	number = int(input("Please Enter a positive number: "))
	if number <= 0:
		raise ValueError("You have not enetered positive number")
		print('The Entered number is: ',number) 
except ValueError as ve:

Please Enter a positive number: -21
You have not entered a positive number
Please Enter a positive number: 8
The Entered number is:  8


  • From the above, we learned the difference between the syntax errors and exceptions
  • You have learned how to handle the raised exceptions and how to implement try, except and finally blocks in different combinations
  • You have learned how to use ‘else’ condition with the ‘try’ block, to know the better workflow please implement else conditions with the ‘try’, ‘except’ and ‘else’ different combinations.
  • You have learned how to manage and capture the program errors in the applications.
  • You have learned python exception handling and basic examples from this article

Please comment us below if any queries and need additional advanced examples.

You can also click here for python exception handling examples.