Python – Exceptions and Error Handlings

If you write a complex python code , it is very important to handle errors and exceptions. While handling files, connecting to database systems and so on , you can be the best programmer in the world and still get errors that is not up to you. When you write a code for infrastructure, you need to raise exceptions and warnings to let other developers to use you code correctly.

In this post, i will go over errors, exceptions, warnings and related topics


You can add warnings to your code.

Simple example

If you run it you will see the following warning message:

You can run it without the warning using one of the following methods

command line:

using PYTHONWARNINGS environment variable

in the code:

if you use one of the above methods with ‘error’ instead of ‘ignore’, you will get an error message and the program execution stops


Error Messages

Python routes its own error messages to stderr but it cannot know which of your messages are errors. You can write to stderr using print command (python 2.7) or function (python 3.6).

The syntax is different so if you want to write version independent code use sys module:


Exception Handling

Sometimes you don’t know if your task completed successfully until you try. For example while accessing a web server it may be offline, so you need to send request and wait for response and after a timeout generate error. Thats why we need exceptions. Exception handling is not error handling, you will not use exception for something you can check for example if you divide x/y , check that y is not zero using if statement and not using exceptions

In Python an exception can be thrown , it is represented by an object (a class derived from the Exception). Throwing an exception transfers control and the function call stack is unwound until a handler capable of handling the Exception object is found

Simple example:

If the file doesn’t exists you will see the following output:

Any exception in the try block transfers control to the except block. If the file exists the except block is ignored:

You can write multiple except block and also multiple exceptions for each block for example:

Note that the first except block that match the exception type will be executed so the order is important. If you place the last except block (except Exception) before any other exception it will catch it

Exception Object

You can use the exception object to get more details about the exception:



Else Block

You can add else block to the try – except blocks. It will run if no exception occurred.

It is similar to add more statements at the end of the try block, the only difference is what happens  if the statement in the else block generate an exception, it will transfer control to the calling function.

For Example:

If the file doesn’t exists the output is:

But if we move the open function to the else block:

The exception is now handled on f1:

The Finally Block

You can add a finally block which is (almost) always executed, even if an exception occurs

Output without exception:

Output with exception

The main use of the finally block is to release resources (locks, files, etc.)

You can write code with try and finally only if you handle the exception in the calling function

Raising Exceptions

You can raise exceptions in your code. It is useful if you don’t want to return normally

For example:

On exception, the program terminated

Writing Your Own Exception Class

To create a new type of exception derive a class from Exception class:

You can add some magic methods to provide useful operations (__str__ for example)

Subscribe to our list








Leave a Reply

Your email address will not be published.