Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Handling | Error Handling
Mastering Python: Annotations, Errors and Environment
course content

Course Content

Mastering Python: Annotations, Errors and Environment

Handling

Let's consider Python tools that help us to control code execution and errors.

Error Handling Structure

There are different keywords are used to control program errors:

  • try: this keyword is used for the code block where we expect the error.
  • except: this keyword is used for the code block executed if an error is raised.
  • else: this keyword is used to perform certain logic if errors are not raised.
  • finally: this keyword is used for the code block that always executes after all structure.

try and except

These are the main keywords for error handling, the try code block waits for errors, and the except catches it:

The interpreter is not stopped after the ZeroDivisionError raising because the except keyword caught it.

Note

Don't try to put all your code inside the try block - this will lead to unexpected consequences and can break the program.

If the try block is executed without errors, the except block will not be executed.

The try block does not roll back executed code. All the code lines before an error are executed:

Note

The try block raises the exactly one error because executing stops after an error.

else and finally

The else and finally blocks are optional and used less often.

You can add and remove comments in the example above to understand how it works.

1. The `try` code block is used to...
2. The `except` code block is used to...
3. The `else` code block is used to...
4. The `finally` code block is used to...

The try code block is used to...

Select the correct answer

The except code block is used to...

Select the correct answer

The else code block is used to...

Select the correct answer

The finally code block is used to...

Select the correct answer

Everything was clear?

Section 3. Chapter 4
We're sorry to hear that something went wrong. What happened?
some-alt