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.
Table of Contents
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:
- Logical – arise due to logical inaccuracies in the software algorithm.
- Syntactic – appear as a result of syntactic errors in the program code.
- 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:
Exception | Description |
---|---|
ArithmeticError | Raised when an error occurs in numeric calculations |
AssertionError | Raised when an assert statement fails |
AttributeError | Raised when attribute reference or assignment fails |
Exception | Base class for all exceptions |
EOFError | Raised when the input() method hits an “end of file” condition (EOF) |
FloatingPointError | Raised when a floating point calculation fails |
GeneratorExit | Raised when a generator is closed (with the close() method) |
ImportError | Raised when an imported module does not exist |
IndentationError | Raised when indendation is not correct |
IndexError | Raised when an index of a sequence does not exist |
KeyError | Raised when a key does not exist in a dictionary |
KeyboardInterrupt | Raised when the user presses Ctrl+c, Ctrl+z or Delete |
LookupError | Raised when errors raised cant be found |
MemoryError | Raised when a program runs out of memory |
NameError | Raised when a variable does not exist |
NotImplementedError | Raised when an abstract method requires an inherited class to override the method |
OSError | Raised when a system related operation causes an error |
OverflowError | Raised when the result of a numeric calculation is too large |
ReferenceError | Raised when a weak reference object does not exist |
RuntimeError | Raised when an error occurs that do not belong to any specific expections |
StopIteration | Raised when the next() method of an iterator has no further values |
SyntaxError | Raised when a syntax error occurs |
TabError | Raised when indentation consists of tabs or spaces |
SystemError | Raised when a system error occurs |
SystemExit | Raised when the sys.exit() function is called |
TypeError | Raised when two different types are combined |
UnboundLocalError | Raised when a local variable is referenced before assignment |
UnicodeError | Raised when a unicode problem occurs |
UnicodeEncodeError | Raised when a unicode encoding problem occurs |
UnicodeDecodeError | Raised when a unicode decoding problem occurs |
UnicodeTranslateError | Raised when a unicode translation problem occurs |
ValueError | Raised when there is a wrong value in a specified data type |
ZeroDivisionError | Raised 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.