07. Exceptions

Arindam BaidyaArindam Baidya
1 min read

Errors and Exceptions

When Python tries to execute code and something goes wrong, Python raises an exception.

Different kind of errors

Throw some selective exceptions

Hierarchy of exceptions

Python 3 has 63 built-in exceptions, which all form a tree hierarchy.

Example

We can write ArithmeticError in place of ‘ZeroDivisionError’. But we will get a general error.

Here, the first matching branch will execute. It means the order of the branch matters.

We can handle two or more exceptions in the same way.

Handle the exception inside the function

Handle the exception outside the function

Here, the function should go under the try block.

Manually raise an exception using raise keyword.

Let’s always raise a ZeroDevisionError in the calculate user input function.

We can also raise without any exception name:

This will re-raise immediately, and we need to handle them using another try-except block.

assert

References

Kodekloud

0
Subscribe to my newsletter

Read articles from Arindam Baidya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arindam Baidya
Arindam Baidya