Python Exception Handling and built-in Exceptions with Examples

Python Exception handling:

Python Exception:- Just imagine a program that has a comparatively deep call hierarchy that means that functions call further sub-functions, which in turn call functions. It is often the case that the parent Functions cannot continue to work correctly if in one of their sub-functions an error has occurred. The information that an error has occurred must be funneled up through the call hierarchy so that each higher-level Function can react to the error and adapt to it.

So far, we have only been able to manage errors that occurred within a function Identify using the return value of the function. It’s a lot of effort connected, such a return value through the function hierarchy upwards to be passed on, especially since these are Python Exceptions. So we would very much spend a lot of code handling rare cases.

For such cases, Python supports a programming concept, exception handling (Eng. »exception handling«) is called. In the event of an error, our sub-function generates then a so-called exception and, figuratively speaking, throws it afterwards above. The execution of the function is now complete. Any super ordinate function now has three options:

  • It catches the Python Exception, executes the code provided in the event of an error and then continues normally. In such a case, notice another parent The Python Exception does not function.
  • It catches the  Exception, executes the code provided in the event of an error is, and throws the Python Exception further up. In such a case, the Execution of this function ends immediately, and the higher-level function has the choice of catching the exception or not.
  • It lets the exception happen without catching it. In this case the execution the function ends immediately, and the higher-level function is in front the choice of catching the exception or not.

So far we have had one such issue

>> abc

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

NameError: name ‘abc’ is not defined

generally spoken of an “error” or an “error message”. This is not entirely correct: In the following we would like to refer to this output as traceback. A traceback is always displayed when an Python Exception is passed through to the top without being caught, but what exactly is an Exception?

An Python Exception is an object that contains attributes and methods for classification and Processing of an error contains. Some of this information is in the traceback displayed, such as the description of the error (“name ‘abc’ is not defined”). An Exception can be caught and handled in the program itself without the the user is aware of it. Should not catch an exception it is output in the form of a traceback, and the program flow will be terminated.

Python Built-in Exceptions:

A number of built-in exceptions exist in Python, for example the ones already known exceptions SyntaxError, NameError or TypeError. Such Python Exceptions are thrown by functions of the standard library or by the interpreter itself. They are built in, which means that they are used at all times in the source code can be:

The Python built-in exceptions are organized hierarchically, that is, they inherit from common base classes. They are therefore in their attribute and method scope largely identical. The following table lists the built-in exception Types and common circumstances under which they occur. The inheritance hierarchy is indicated by the indentation depth of the type name.

Built-in Exceptions:

Python Built-in Exception BaseException:

  • Base class of all built-in exception types

Python Built-in Exception  SystemExit:

  • When closing the program through sys.exit. This exception does not cause a traceback.

Python Built-in Exception  KeyboardInterrupt:

  • when closing the program with a key combination(usually with (Ctrl + C)

Python Built-in Exception  GeneratorExit:

  • when stopping a generator

Python Built-in Exception:

  • Base class of all “normal” exceptions. Also all self-defined exception types should inherit from

Python Built-in Exception  StopIteration:

  • when calling the method next of an iterator, if there is no next element

Python Built-in Exception  ArithmeticError:

  • Base class of exception types for errors in arithmetic operations

Python Built-in Exception   FloatingPointError:

  • on a failed floating point operation

Python Built-in Exception  OverflowError

  • in an arithmetic calculation, whose Result too large for the data type used

Python Built-in Exception  ZeroDivisionError:

  • when dividing by zero AssertionError in the event of a failed assert

Python Built-in Exception  AssertionError:

  • on a failed assert statement

Python Built-in Exception   AttributeError

  • when accessing a nonexistent attribute

Python Built-in Exception  BufferError

  • for a failed operation on a Buffer data type.

Python Built-in Exception  EnvironmentError

  • Base class of exception types for errors that happen outside of the Python system.

Python Built-in Exception  IOError:

  • on a failed I / O operation, for example a screen input or output

Python Built-in Exception  OSError

  • if there are errors in the os module

Python Built-in Exception WindowsError

  • in the case of a Windows-specific error

Python Built-in Exception  VMSError

  • in the event of a VMS specific error

Python Built-in Exception  EOFError

  • when the built-in function input is an end of file (EOF for end-of-file) is signaled, without being able to read data beforehand

Python Built-in Exception  ImportError

  • if the import statement fails, for example, if there is no module with the specified Name exists

Python Built-in Exception  LookupError

  • Base class of exception types for errors in Key or index access

Python Built-in Exception  IndexError

  • in the case of a sequence access with an invalid index

Python Built-in Exception  KeyError

  • with a dictionary access with an invalid key

Python Built-in Exception  MemoryError

  • if not enough memory to run an operation is present

Python Built-in Exception  NameError:

  • if an unknown local or global Identifier is used

Python Built-in Exception  UnboundLocalError:

  • if in a function or method a local Reference is used before its an instance was assigned

Python Built-in Exception  ReferenceError:

  • when accessing an object that has been garbage Collection has already been released

Python Built-in Exception  RuntimeError:

  • in the event of a failure caused by none of the others Exception types is covered

Python Built-in Exception  NotImplementedError:

  • Base classes throw this exception from methods out that of a derived class need to be implemented.

Python Built-in Exception  SyntaxError:

  • if there is a syntax error in the program or in a code passed to exec or eval

Python Built-in Exception  IndentationError:

  • Base class of the exception types for errors incorrect indentation of the source code

Python Built-in Exception  TabError:

  • if tabs are incorrectly mixed and spaces for indentation

Python Built-in Exception:

  • in the event of an internal error in the Python interpreter

Python Built-in Exception  TypeError:

  • for an operation on an instance one for it unsuitable data type

Python Built-in Exception  ValueError:

  • during an operation on an instance that does a suitable type, but an inappropriate one Has value

Python Built-in Exception  UnicodeError:

  • in the event of incorrect encoding or decoding of Unicode character

Python Built-in Exception  UnicodeDecodeError:

  • in the event of a Unicode-specific error in a Decoding

Python Built-in Exception  UnicodeEncodeError:

  • in the event of a Unicode-specific error in a Encoding

Python Built-in Exception  UnicodeTranslateError:

  • in the event of a Unicode-specific error in a translation

Python Built-in Exception  Warning:

  • Base class of the warning types

Python Built-in Exception  DeprecationWarning

  • when using a deprecated Functionality

Python Built-in Exception  PendingDeprecationWarning:

  • when using one as obsolete in the future classified functionality

Python Built-in Exception  RuntimeWarning:

  • in circumstances that lead to runtime errors could, for example, version differences

Python Built-in Exception  SyntaxWarning:

  • at a syntax that is problematic but valid

Python Built-in Exception  UserWarning:

  • Base class for self-defined warnings

Python Built-in Exception  FutureWarning:

  • when using functionalities that will change in future versions

Python Built-in Exception ImportWarning:

  • for problems caused by integrating a Module

Python Built-in Exception UnicodeWarning:

  • for Unicode-specific problems

Python Built-in Exception BytesWarning:

  • for byte-specific problems

Python Built-in Exception ResourceWarning:

  • if there are problems with the use of resources


The BaseException class is the base class of all Python Exceptions and thus represents a Basic functionality available that is available for all Python Exception types. For this Reason it should be discussed here. The basic functionality that BaseException provides consists of an essential one Attribute named args. This is a tuple in which all parameters that were passed to the Python Exception when it was instantiated. With these parameters it is then possible later when catching the Exception, detailed Get information about the error that has occurred. Using the The following example demonstrates the args attribute:

 Throwing a Python Exception:

So far we have only considered Python Exceptions that were generated in the event of an error by the Python Interpreter were thrown. However, it is also possible using the raise statement throw an exception yourself:

To do this, the keyword raise is written, followed by an instance. This may only be an instance of a class derived from BaseException. Throwing instances other data types, especially strings, are not possible:

In the following section we would like to discuss how exceptions in the program can be intercepted so that they do not end in a traceback, but to the Python Exception handling can be used.

Catching a Python Exception:

This section is about how to get thrown into a subfunction Python Exception can be caught in the call levels above. The Catching an  Exception is necessary in order to react to the error that has occurred can. Imagine a program that takes data from a user-specified File reads. The program uses the following for this purpose, at the moment very simple function get that returns the opened file object:

If no file with the specified name exists, the built-in Function open an IOError Python Exception. Since the get function does not respond to this Python Exception responds, it is passed up in the call hierarchy and caused and finally an early termination of the program.

Incorrect user input is a problem to deal with when writing a interactive program. The following variant of the function get catches an IOError  Exception thrown by open and takes place in this case of the opened file object returns the value None.

A try / except statement is used to catch an Python Exception. Such The instruction consists of two parts:

  • The try block is introduced by the keyword try, followed by a Colon and, indented one level further, any code block. This code block is executed first. If there is a  Exception occurs, its execution is terminated immediately and the except branch of the instruction executed.
  • The except branch is introduced by the keyword except, followed by an optional list of Python Exception types for which this except branch is executed shall be. Note that there are multiple Python Exception types in the form of a Tuples must be specified. You will see an example of this later see. After the list of  Exception types, the keyword as followed by a freely selectable identifier. Here you put the name under which you access the Exception instance caught in the except Branch can access. In this way, for example, you can access the in access information stored in the args attribute of the Exception instance.This is followed by a colon and, indented one level further, any one Code block. This code block is only executed if within the try block one of the listed  Exceptions was thrown.

A basic try / except statement has the following structure:





exception Exception type as identifier:




Let’s get back to our example function get. It is quite possible that with a function call for name incorrectly not a string, but for example a list is passed. In such a case, no IOError but a TypeError thrown, which has not yet been caught by the try / except statement:

The function should now be extended so that a TypeError is also caught and then also None is returned. For this we essentially have three options. The first is to get the list of  Exception to be caught Types in the existing except branch to extend the TypeError. Notice while having two or more Python Exception types in the head of an except branch as a tuple must be specified.

This is simple and leads to the desired result in the example chosen. Put However, imagine you wanted different code based on the type of Python Exception To run. To achieve such behavior, a try / except statement have any number of except branches.

The third – less elegant – option is to throw all kinds of Python Exceptions at once intercept. To do this, an except branch is used without specifying an Python Exception type written:

An Python Exception is nothing more than an instance of a certain class. Therefore The question arises whether and how one can access the thrown instance obtained. This is done by specifying the as already mentioned Identifier part possible in the header of the except branch. Under the one specified there We can now refer to the thrown exception within the code block. Access instance:

In addition, a try / except statement can be used via an else and finally Branches that can only appear once per statement. The code block associated with the else branch is executed if no Exception occurred is, and the code block belonging to the finally branch is always after Handling of all Python Exceptions and after executing the corresponding else Branch executed regardless of whether or which Exceptions occurred previously. This finally branch is therefore particularly suitable for things that are always done need, such as closing a file object.

Both the else and finally branches must come to the end of the try / except statement to be written. If both branches occur, the else branch must come before are in the finally branch.

Finally, a few notes on how a try / except statement is executed is: First the code belonging to the try branch is executed. Should If an exception is thrown within this code, the corresponding except branch executes associated code. Is not a suitable except branch exists, the Python Exception is not caught and ends if it is is not intercepted anywhere else than traceback on the screen. Should in the try- Branch no exception are thrown, none of the except branches are executed, but the else branch. The finally branch is always executed at the end.

Python Exceptions that are thrown within an except, else or finally branch, are treated as if the entire try / except statement threw this Exception. Exceptions thrown in these branches cannot be from following except branches of the same statement can be caught again. It is however, possible to nest try / except statements:

A TypeError is thrown in the try branch of the inner try / except statement, which is not intercepted by the instruction itself. The Python Exception then wanders, figuratively speaking, go one level up and go through the next try / except statement. In this the thrown TypeError is caught and a corresponding Message issued. The output of the example is therefore: A TypeError has occurred, no traceback is displayed.

Own Python Exceptions:

When throwing and catching exceptions, you are not on the built-in sentence limited by exception types, but you can create new types yourself. All you need to do is create your own class, which is used by the Python Exception Base class inherits exception, and then further attributes and Add methods to handle your exception.

The following is an example of how to create your own exception type be demonstrated. To do this, we first define a rudimentary account class, which is the only operation that supports withdrawing a certain amount of money.

In this implementation of the class it is possible to overdraw the account at will. In a more sophisticated variant, overdrafting the account is to be prevented and when trying to withdraw more money than is available, one self-defined exception can be thrown. To do this, we first define one of class derived from the base class Exception and add attributes for the account balance and the amount to be withdrawn.

Then we modify the method of withdrawing the class account so that at An AccountException instance is thrown for an invalid withdrawal process.

The additional information passed to the class constructor will be not displayed in traceback:

They only come into play when the exception is caught and processed:

This code catches the Python Exception that has arisen and then issues an error message out. Based on the additional information that the class provides through the attributes provides the account balance and amount, the previous withdrawal process reconstruct. The output of the example is:

Account balance: 1000 €

Withdrawal of 2000 € not possible.

This also means a self-defined Python Exception with further information may contain an error message, it must implement the Magic Method str:

A traceback caused by this exception looks like this:

Re-throwing a Python Exception:

In some cases, especially when there is a deep function hierarchy, it makes sense to use a Catch the exception, start the error handling intended for this case and then throw the exception again. The following example:

In the example, the function function1 is called, which in turn calls function2, in which the function function3 is called. So it is a total three nested function calls. At the core of these function calls, in function3, a TypeError exception is thrown. This Python Exception will not intercepted, so the associated traceback looks like this:

As expected, the traceback describes the function hierarchy at the point in time the raise statement. This list is also called the call stack. The idea behind the Python Exception principle is that there is an exceptions that works up in the call hierarchy and is intercepted at each station can. In our example, the function function1 should raise the TypeError exception so that they can receive special error handling tailored to the TypeError can perform. For example, a file object could then be closed will. After function1 has performed its internal function error handling the Exception should be passed further up. For this she is thrown again, as in the following example:

In contrast to the previous example, the traceback that now appears looks like this:

You can see that this traceback provides information about the context of the second raise Contains instruction. However, these are of no importance at all, but rather a by-product error handling within the function function1. It would be optimal if, despite the temporary catching of the exception in function1, the resulting Traceback described the context of the original raise statement. To do that a raise statement is written without specifying an exception type:

The traceback output in this example looks like this:

You can see that this is the stack trace of the point at which the exception was originally thrown. The traceback thus contains the required Information about where the error actually occurred.

Python Exception Chaining:

Occasionally one gets confused within an except branch comes to throw another exception. The problem with this is that the exception originally caught in this except branch is lost. This is problematic since the occurrence of this exception may have contributed to it gen that the second exception had to be thrown. This confusing The situation should be clarified using an example:

The try branch tries to access the 128th element of a 3-element list, which provokes an IndexError exception. This is in the except branch caught and also a RuntimeError exception with an expressive Thrown error message. This RuntimeError exception becomes the previously caught IndexError exception appended, which is also reflected in the resulting traceback reads:

The above exception was the direct cause of the following Exception:

The final exception is a RuntimeError exception. You cannot be caught by an except branch, the IndexError exceptions treated. The use of the raise / from syntax was actually not necessary in the above example, because automatically for exceptions that are thrown from except branches the previous exception is appended. Should you get the exception But want to use chaining outside of else branches, you have to use them from Use syntax. In conclusion, the techniques presented here for exception handling help immensely in writing structured and readable code so that You should internalize them.

Related Article:

Python Encapsulation

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: