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

Detailed except

You can catch certain types of errors using the except keyword.

There are moments when you need to catch certain errors and handle them. For example, you need to handle the TypeError, but executing raises the ZeroDivisionError. If you handle ZeroDivisionError like the TypeError - it is a bug:

In the example above, the ZeroDivisionError was raised by the 5 / 0 expression. The except catch it and print the wrong message.

To catch the certain error, you should write the error name after the except keyword:

Now, the except keyword not caught the ZeroDivisionError.

You can catch certain in the row by the multiply except usage:

Error info usage

You can save the error using the as keyword after the except and error type. You should name this error, and you can use it like the variable:

In the example above, the caught error is saved into the error variable by the as keyword.

To catch any exception with the as keyword, you can use the Exception object:

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

Reraising

You can reraise the exception, which can be needed for specific cases. To reraise the exception, you should use the raise keyword without anything:

Everything was clear?

Section 3. Chapter 5
course content

Course Content

Mastering Python: Annotations, Errors and Environment

Detailed except

You can catch certain types of errors using the except keyword.

There are moments when you need to catch certain errors and handle them. For example, you need to handle the TypeError, but executing raises the ZeroDivisionError. If you handle ZeroDivisionError like the TypeError - it is a bug:

In the example above, the ZeroDivisionError was raised by the 5 / 0 expression. The except catch it and print the wrong message.

To catch the certain error, you should write the error name after the except keyword:

Now, the except keyword not caught the ZeroDivisionError.

You can catch certain in the row by the multiply except usage:

Error info usage

You can save the error using the as keyword after the except and error type. You should name this error, and you can use it like the variable:

In the example above, the caught error is saved into the error variable by the as keyword.

To catch any exception with the as keyword, you can use the Exception object:

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

Reraising

You can reraise the exception, which can be needed for specific cases. To reraise the exception, you should use the raise keyword without anything:

Everything was clear?

Section 3. Chapter 5
some-alt