Mike Driscoll Profile picture
Jan 20 โ€ข 15 tweets โ€ข 7 min read
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

Jan 20
You can use Pycryptodome to encrypt a file and decrypt it.

In this example, you use RSA encryption to encrypt a file with #Python
Now let's decrypt the file using Pycrytodome! ๐Ÿ๐Ÿ”ฅ

Here's how to do it:
PyCrytodome supports generating RSA keys with 2048-bits and higher

pycryptodome.org/src/examples#eโ€ฆ
Read 4 tweets
Jan 13
Today I am going to show you how to create 7๏ธโƒฃ different file types with #Python:

๐Ÿ Text file
๐Ÿ CSV
๐Ÿ XML
๐Ÿ JSON
๐Ÿ Tar file
๐Ÿ PDF
๐Ÿ Excel

Join me for this fun ๐Ÿงต๐Ÿ‘‡
1๏ธโƒฃ Creating a text file with #Python is a breeze! The recommended method is to use Python's `with` statement as it will automatically close the file for you

That means you can create a text file with TWO lines of code if you want to:
2๏ธโƒฃ Creating a CSV file with #Python can be accomplished using the `csv` module

Here's a small example:
Read 16 tweets
Jan 11
#Python 3 has had asynchronous capabilities since 3.4. So let's talk about that today!

๐Ÿงต๐Ÿ๐Ÿ‘‡
Your first stop when learning about async in #Python is the official documentation.

There you will learn about the following:

๐Ÿ The `asyncio` module
๐Ÿ The `async` and `await` keywords

docs.python.org/3/library/asynโ€ฆ
The #Python documentation has a nice "Hello World" example for async.

In this example, you see how to create an asynchronous function, sleep and print out some strings: Image
Read 10 tweets
Dec 23, 2022
#Python has TONS of great packages and frameworks.

In this thread, I am going to highlight just a few of the THOUSANDS that are available to you on pypi.org

๐Ÿ๐Ÿงต๐Ÿ‘‡
Python has lots of great cross-platform GUI packages:

๐Ÿ PySimpleGUI @PySimpleGUI
๐Ÿ PyQt / PySide
๐Ÿ wxPython
๐Ÿ Tkinter
๐Ÿ @DearPyGui
๐Ÿ EasyGUI
#Python also has a couple of GUI frameworks for mobile development (i.e. iOS and Android):

๐Ÿ”ฅ Kivy @kivyframework
๐Ÿ Toga from @PyBeeWare

I have heard PyQt also supports mobile, but haven't been able to verify it
Read 10 tweets
Dec 21, 2022
Do you ever need to redirect stdout with #Python?

In this mini-thread, I will show you 3๏ธโƒฃ different methods to redirect stdout!

๐Ÿงต๐Ÿ๐Ÿ‘‡
1๏ธโƒฃ Re-assign `sys.stdout` to a file handle

In this example, you open a file and reassign `sys.stdout` to that file handle.

Now when you call the `print()` function, it writes to a file instead of stdout!

Don't forget to revert your changes at the end!
2๏ธโƒฃ Use a context manager!

Here you use `contextlib.contextmanager` to automatically redirect stdout and then revert the redirection.

This is a nice way to decorate functions that you want to write to a file without modifying all of them.
Read 5 tweets
Dec 20, 2022
#Python has had the concept of context managers for a loooong time!

Let's talk about context managers again!

๐Ÿงต๐Ÿ๐Ÿ‘‡
The `with` statement, which is the normal way for working with context managers, was added back in Python 2.5!

Here is a pretty common example of using a context manager:
The beauty of a context manager is that they allow you to do some setup and teardown automatically.

The downside is that is abstracted away and can sometimes make the code less obvious when debugging
Read 8 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 on Twitter!

:(