Errors and Exceptions in Python

It is a common occurrence to encounter errors or warnings while working with Python, or various different programming languages. These errors may occur due to a wide variety of reasons. The process of handling exceptions and errors in Python can significantly increase the resilience of program code to failures, due to which the program’s workflow can be completely stopped or result in wrong output. To understand how the error handling process should be carried out correctly, it is necessary to consider the most common kind of erroneous situations.

Errors vs Exceptions in Python

Before looking at the process of exception handling and what it is for, it is important to understand how errors in Python differ from exceptions. The main differences are:

  • Compared to exceptions, errors cannot be handled.
  • Initially, errors indicate critical moments in the performance of the program and, according to the algorithm, it should not intercept them. It is advisable to intercept the exception in order to restore the operability of the program code, to make it more resistant to possible problems.
  • Not all errors stop the program’s workflow instantly.

Considering the various issues that may occur in Python, errors or exceptions can be broadly categorized into three:

  1. Logical – arise due to logical inaccuracies in the software algorithm.
  2. Syntactic – appear as a result of syntactic errors in the program code.
  3. Exceptions – arise from user actions that do not match the software algorithm.

Logical Errors in Python

They are the most difficult to fix, because in this case, externally, the program works without errors. But it doesn’t work exactly the way (and sometimes not at all) as the programmer intended but the Python interpreter. It will not notice – all the rules of coding are followed. Finding such an error can take quite a long time, especially if the program is large. Let us look at an example of logical(semantic) error.

#Print number of sheep up until 100.
sheep=1
while sheep<100:
    print("%i sheep"%sheep)

The program the while loop will compile and run without errors however, the end result is not what was intended by the programmer. The loop will continue indefinitely and may even crash the Python compiler.

Syntax Errors in Python

The programmer can make a mistake in the use of the programming language itself. In other words, express yourself the way you shouldn’t. For example, start a variable name with a number or forget to put a colon in the header of a complex statement. Such errors are called Syntactic/Syntax errors , they violate the syntax and punctuation of the language. The Python interpreter, upon encountering an erroneous expression, does not know how to interpret it. Therefore, it stops the execution of the program and displays an appropriate message indicating the location of the error:

print 'Hello, world!'
Output:
  File "main.py", line 1
    print'Hello, world!'
         ^
SyntaxError: invalid syntax

Exceptions in Python

Exceptions in Python are those errors that are not critical for the entire working file, but occur during the execution of program code. In situations where the embedded script cannot handle the exception, the program’s workflow must be forced to stop. Special attention should be paid to the hierarchy of exceptions.  The programmer can specify within the code how various exceptions should be handled. Python comes with various built-in Exceptions.

int('qwerty')
Output:
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    int('qwerty')
ValueError: invalid literal for int() with base 10: 'qwerty'

In the above example the output returns the ‘ValueError‘ built-in exception which indicates that an incorrect value has been received. The various built-in exceptions in Python are:

ExceptionDescription
ArithmeticErrorRaised when an error occurs in numeric calculations
AssertionErrorRaised when an assert statement fails
AttributeErrorRaised when attribute reference or assignment fails
ExceptionBase class for all exceptions
EOFErrorRaised when the input() method hits an “end of file” condition (EOF)
FloatingPointErrorRaised when a floating point calculation fails
GeneratorExitRaised when a generator is closed (with the close() method)
ImportErrorRaised when an imported module does not exist
IndentationErrorRaised when indendation is not correct
IndexErrorRaised when an index of a sequence does not exist
KeyErrorRaised when a key does not exist in a dictionary
KeyboardInterruptRaised when the user presses Ctrl+c, Ctrl+z or Delete
LookupErrorRaised when errors raised cant be found
MemoryErrorRaised when a program runs out of memory
NameErrorRaised when a variable does not exist
NotImplementedErrorRaised when an abstract method requires an inherited class to override the method
OSErrorRaised when a system related operation causes an error
OverflowErrorRaised when the result of a numeric calculation is too large
ReferenceErrorRaised when a weak reference object does not exist
RuntimeErrorRaised when an error occurs that do not belong to any specific expections
StopIterationRaised when the next() method of an iterator has no further values
SyntaxErrorRaised when a syntax error occurs
TabErrorRaised when indentation consists of tabs or spaces
SystemErrorRaised when a system error occurs
SystemExitRaised when the sys.exit() function is called
TypeErrorRaised when two different types are combined
UnboundLocalErrorRaised when a local variable is referenced before assignment
UnicodeErrorRaised when a unicode problem occurs
UnicodeEncodeErrorRaised when a unicode encoding problem occurs
UnicodeDecodeErrorRaised when a unicode decoding problem occurs
UnicodeTranslateErrorRaised when a unicode translation problem occurs
ValueErrorRaised when there is a wrong value in a specified data type
ZeroDivisionErrorRaised when the second operator in a division is zero

Hence, we have gone through the various forms of errors, definitions and the various built-in exceptions. If you learn how to handle various exceptions in time, you can stop the program’s workflow and make your code resistant to various problems. Additionally, the exception handling process prepares the code for deployment.

Leave a Comment