What is a syntax error in Python

Errors and Exceptions¶

, and - error handling¶

The keyword is used to initiate exception handling: If the block does not run through without errors, the error can be caught by means of an instruction; in this case all statements of the respective block are executed.

Optionally, in addition to one and one or more instructions, an instruction can also be specified, which is executed exactly when the instruction none Has triggered an error:

try: # This statement can trigger a FileNotFoundError: file = open ('/ tmp / any_file.txt') exceptFileNotFoundError: print ("File not found!") exceptIOError: print ("File not readable!") else: # Read file if no error occurred: data = file.read () finally: # always execute this statement: file.close ()

In addition to and, you can optionally specify a block; Code that is within this block is always executed at the end of the exception handling, regardless of whether the block was executed without errors or an exception occurred.

The statement

Exception handling is particularly important when files are to be read in or written. If an error occurs during processing, the object must nevertheless be closed again. With a "classic" and notation, this looks something like this:

# Create file object: myfile = open ("filename.txt", "r") try: # Read the file and display the content on the screen: content = myfile.read () print (content) finally: # Close the file object: f .close ()

This routine, which occurs relatively frequently, can also be written in a shorter and more elegant way using a statement:

withopen ("filename.txt", "r") asmyfile: content = myfile.read () print (content)

Here, Python also tries to execute the block just like a block. The method is, however, much more "object-oriented": The instruction specified in the statement creates an instance of an object, in the example above an object; This object can be accessed within the block using the identifier specified after the keyword.

The two methods and should be defined in the class of the object created by the statement, which contain statements that are called immediately at the beginning or at the end of the block. For example, objects have a method in which the respective file is closed again.

- Trigger errors yourself

The keyword can be used to trigger an exception at the relevant point in the code itself. This is useful, among other things, for intercepting incorrect entries at an early stage when interpreting user input.

For example, if a user enters a letter instead of a number, this can very likely lead to errors when calling up the further processing function. However, since the error arose during the entry, the corresponding error message (on) should also be triggered at this point.