Mike Driscoll Profile picture
Jan 20, 2023 โ€ข 15 tweets โ€ข 7 min read โ€ข Read on X
Today is a great day to learn about exception handling in #Python!

Let's find out how they work!

๐Ÿงต๐Ÿ๐Ÿ‘‡
#Python handles exceptions using the `try/except` keywords.

You can optionally add `finally` and `else` to the mix too!

Here's an example that uses all of them:
#Python has the concept of the "bare except". What that means is that you catch ALL exceptions.

You can do this by catching Exception, which is the base class of ALL other exceptions.

Or you can just not specify an exception type all!
#Python Pro Tip: Do NOT do this! โš ๏ธ

When you catch all the exceptions, you can hide bugs that you want to actually catch!

This leads to difficult and frustrating debugging.

You should ALWAYS use specific exception types whenever possible!
What happens when #Python catches an exception? That's up to you.

Here you catch the `ZeroDivisionError`. You handle it by printing out that you caught it.

In a production application, you might close a database connection, log the issue or rollback a transaction
Now let's rewrite the code to catch an `OSError`.

Does that catch a zero division exception?

No! Of course not!

So this time, you get a traceback and your code fails!
You can fix this problem by catching both `OSError` and `ZeroDivisionError` though!

But now you have a new problem! How do you know which exception was thrown here?
One way to figure out which exception is thrown is to use #Python's `as` keyword to give us access to the `exception` object.

Then you can print out which exception was thrown! ๐Ÿ๐Ÿ”ฅ
You can extract additional information about the exception from the `exception` argument, such as what arguments were passed to it:
#Python lets you use `finally` to run code every time the `try/except` is run, regardless of whether or not you catch the exception.

In this example, you use the `finally` statement to close the file handler
You might want to catch an exception in #Python and log it and do some cleanup.

But you don't want the program to continue. In those situations, you could call `sys.exit()` or you could re-raise the exception.

In this example, you do the latter:
#Python will do a special type of traceback when an exception is thrown during the handling of another exception.

This is what that looks like:
Want to create your own exception in #Python? You can do that by subclassing `Exception`! ๐Ÿ๐Ÿ”ฅ

Here's an example:
You can learn more about exception handling in my tutorial @mousevspython

blog.pythonlibrary.org/2020/06/17/pytโ€ฆ
Thanks for joining me in this thread on #Python exception handling!

Follow me for more great content on the Python programming language! ๐Ÿ

โ€ข โ€ข โ€ข

Missing some Tweet in this thread? You can try to force a refresh
ใ€€

Keep Current with Mike Driscoll

Mike Driscoll Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @driscollis

Feb 1
Did you know that #Python supports SQLite in the standard library? That's right. You don't need to install anything! ๐Ÿ๐Ÿš€

Let's talk a little about that!

๐Ÿงต๐Ÿ‘‡
If you have a pre-existing SQLite database file, you can use #Python's `sqlite3` module to connect to it

Here's how: Image
If you want to create a new SQLite database with #Python, you can use the same syntax that you'd use to connect to a pre-existing one.

Then create a cursor object and create your table, like this: Image
Read 8 tweets
Nov 21, 2023
Today is a great day to talk about #Python lambdas!

Let's learn about them in a thread

๐Ÿ๐Ÿงต๐Ÿ‘‡
A Python lambda is a one-line anonymous function.

Rule #1 is do NOT assign a lambda to a variable.

When you do that, it's no longer an anonymous function. You should just create a regular function at that point Image
If you want to run a lambda in your REPL, wrap it in parentheses, like this: Image
Read 9 tweets
Mar 23, 2023
Want to create a copy of a #Python list? Use Python's `copy()` method!

Note: Watch out if your list contains lists of dictionaries. In those cases, you might be better off using copy.deepcopy()
But be careful! If your list contains a mutable object, like another list or a dictionary, you may encounter some unexpected behavior.

In the following example, you `copy()` the list. Then you modify the nested dictionary in the copy, but that also changes the original list!
You can fix this behavior by using Python's `copy` module. It provides a deepcopy() function that you can use which will make a deep copy of the ENTIRE list!
Read 4 tweets
Mar 22, 2023
#Python generators aren't talked about enough.

So let's talk about them today!

๐Ÿงต๐Ÿ๐Ÿ‘‡
According to the #Python wiki, "Generator functions allow you to declare a function that behaves like an iterator"

One of their best use cases is to chunk through large data sets a piece at a time, which prevents you from running out of memory.

wiki.python.org/moin/Generators
To create a generator in #Python, you need to use the `yield` keyword instead of `return` inside a function.

Generators will continue to yield values until the generator is exhausted.

The following example will continue to yield numbers for as long as you call it: Image
Read 10 tweets
Mar 21, 2023
My 11th #Python book is now available! ๐Ÿ๐Ÿคฏ

Test your Python skills and knowledge with over 100 PYthon quizzes. Answers are included if you get stuck!

Available on Amazon, Leanpub, and Gumroad (see following tweets)
Get my 11th #Python book, The Python Quiz book on Amazon in the following formats:

๐Ÿ Kindle
๐Ÿ Paperback

amazon.com/dp/B0BVT8DZV1
You can find The Python Quiz Book on @gumroad too in the following formats:

๐Ÿ epub
๐Ÿ PDF

driscollis.gumroad.com/l/pyquiz
Read 4 tweets
Mar 17, 2023
Starting in Python 3.7, the `breakpoint()` built-in function was added

It is defined in PEP 553 and simplifies adding a breakpoint to your code

#python_builtins_by_driscollis

๐Ÿงต๐Ÿ๐Ÿ‘‡
You can read about the `breakpoint()` function for Python here:

python.org/dev/peps/pep-0โ€ฆ
Here is some sample code showing how to use the `breakpoint()` function in your Python code
Read 6 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(