Properly responding to errors Exception handling in Python
Error and exception handling also plays an important role in a Python program. Because superordinate functions continue to work even if errors occur in subordinate functions.
Companies on the topic
Exception handling also ensures in Python that a program continues to run despite faulty functions.
(Image: Johnson Martin)
If functions call subfunctions, it can happen again and again that errors occur in the subfunctions. Here it is important that, on the one hand, the higher-level functions continue to function. On the other hand, it must also be ensured that the subfunction communicates the error upwards, so that the superordinate function can react accordingly.
So, parent functions must always be able to manage and handle errors from functions that they call in turn. If only one function is used and reports an error, it is easy to handle due to its return value. However, if many functions are in use and complex nesting is also present, it certainly plays a role how the higher-level functions react to errors of other functions.
Exceptions in Python
Python has internal mechanisms to detect exceptions in the program code. Higher-level functions receive corresponding feedback and can react to the exception.
The function can take the exception, respond to the error as the programmer intended, and proceed with its work. If there is a nested structure, it is possible to additionally forward the error to further, higher-level functions. This function can also react to the error again and set the further transmission.
Child functions that receive errors from other child functions can also forward them without their own error handling. The parent function is then able to decide whether it should perform error handling or whether the error is directed further up.
Python knows several exceptions, including SyntaxError, NameError, and TypeError. These exceptions can also be used in source code:
>>> NameError
<class 'NameError'>>>> SyntaxError
<class 'SyntaxError'>
>>> TypeError<class 'TypeError'>
All exceptions are grouped in the BaseExceptions base class. The “args” attribute of BaseException returns the parameters passed on the exception. This helps with troubleshooting, as it also makes it clear which parameters may be to blame for the error:
a=BaseException(1,2,3,4,5,6,7)
a.args
The command then outputs (1,2,3,4,5,6,7).
Examples of exception expiration
In simple terms, this means that if a function A calls the function B in the program and this starts the function C, then it may well happen that an error occurs in function C. If the program code in function C does not handle the error, the interpreter forwards the exception to function B and then to function A.
If an error occurs in Python, the interpreter stops the program and passes the error to the process or function. If there is program code that performs the handling of the error, the program continues to run. If no handling of the occurring error is provided, the Python program crashes. This would be the case if none of the three functions defined error handling for the C function.
Python can handle error messages with try/except statements. To do this, the code is integrated into the try scope, and the exception handling code is included in the except clause:
try:
Anweisung 1
Anweisung 2
Anweisung 3except:
Anweisung 1
Anweisung 2
Anweisung 3
For a better overview, try/except blocks as well as the code blocks arranged underneath should be indented. If an exception occurs in the Try code block, the code continues with the commands from the Except code block. Basically, the ExceptionTypes that should be handled by this block should also be specified via the Except block, for example:
except (FileNotFoundError, TypeError):
If no Exception Type is specified in the code, except handles all exceptions that occur. This rarely makes sense, since not all errors are interceptable in the code block. It makes more sense to define individual code blocks for the individual exception types.
Of course, it is also necessary to create a separate except block for all exception types. At the end of the blocks, an else and finally branch can be used to define what should happen if the exception cannot be caught by an except block.
The Finally branch at the end is executed in any case if a try block has been terminated with or without exceptions. In many cases, finally is used to release resources reserved by the code block, for example:
try:
f = open("test.txt",encoding = 'utf-8')finally:
f.close()
Create your own exceptions
It is also possible to create your own exceptions based on existing exception types. For this, “raise” is used:
raise SyntaxError("Hallo Welt")
The command outputs the following information in this case:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
raise SyntaxError("Hallo Welt")
File "<string>", line NoneSyntaxError: Hallo Welt
Another example is:
raise KeyboardInterrupt
In parallel, there is the possibility to use exceptions for which there is no built-in ExceptionType. You can also define your own types in Python. To do this, a separate class is created and the ExceptionType is defined, for example:
class CustomError(Exception):
pass
This exception can also be created manually with raise:
raise CustomError
(ID:47393119)