Is there a way to handle errors thrown by third party modules in Python?

Even with a try/except block, it doesn't seem that Python will catch errors thrown by a function or module called in that block. This doesn't make sense. Is there a specific syntax for it? I can't seem to catch the UnicodeDecodeError that BeautifulSoup throws. I just want to be able to catch the error and copy the contents of temp to temp1 when BeautifulSoup can't read the file.

from bs4 import BeautifulSoup
with open('/mnt/data/opendata/work/temp.txt', 'r') as f:
    contents = f.read()
    try:
        soup = BeautifulSoup(contents, 'lxml')
        with open('/mnt/data/opendata/work/temp1.txt', 'w') as f1:
            f1.write(str(soup))
    except:
        with open('/mnt/data/opendata/work/temp1.txt', 'w') as f1:
            f1.write(contents)


Read more here: https://stackoverflow.com/questions/64960115/is-there-a-way-to-handle-errors-thrown-by-third-party-modules-in-python

Content Attribution

This content was originally published by MahaVailo27 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: