A Short Guide to Try/Except Blocks in Python

Both TypeError and ZeroDivisionError exist in this code just above.

We will do something like:try: print(4/0) print(12+"string")except (TypeError, ZeroDivisionError): print("This an error.

")Custom ExceptionsYou may want to use your own custom exceptions.

You can do it like this:try: x = 'something' if x == 'something': raise Exceptionexcept Exception: print("x is something")Output of this code is:x is somethingIn this example, I defined a string called x.

And I just wanted to throw an error if x is something.

This is just an example; you may use it for another case when needed.

And FinallyIn both cases, whether you catch an error or not, this will execute.

try: print(4/0)except ZeroDivisionError as e: print(e)finally: print("I will always execute")We caught a ZeroDivisionError.

And the output is:division by zeroI will always executetry: print(4/1)except ZeroDivisionError as e: print(e)finally: print("I will always execute")We didn’t catch any ZeroDivisionError as it is okay to divide 4 by 1.

The output is:4.

0I will always executeAs it is clear that finally works in both cases.

Thank you for reading.

.

. More details

Leave a Reply