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)
BeautifulSoup
that's throwing the error? ifopen
orwrite
throw an error in your example within theexcept
block they will be uncaught – JeffUK Nov 22 '20 at 22:30