For example, I have this code snippet which does some some HTML parsing for me.
from bs4 import BeautifulSoup
class Parser:
def __init__(self, html_data=None):
if html_data:
self.bs = BeautifulSoup(html_data, 'html.parser')
def setBS(self, html_data):
self.bs = BeautifulSoup(html_data, 'html.parser')
def getLinksByID(self, target_id):
elements = self.bs.find_all(id=target_id)
links = []
for element in elements:
try:
links.append(element.find('a')['href'])
except TypeError:
pass
return links
def getLinksByClass(self, target_class):
elements = self.bs.find_all(class_=target_class)
links = []
for element in elements:
try:
links.append(element.find('a')['href'])
except TypeError:
pass
return links
I am having problem of deciding when to use a Try-Except statements instead of If-Else statements and vice versa when handling exceptions.
For example instead of doing this
def __init__(self, html_data=None):
if html_data:
self.bs = BeautifulSoup(html_data, 'html.parser')
should I do this
def __init__(self, html_data=None):
try:
self.bs = BeautifulSoup(html_data, 'html.parser')
except:
pass
both works but I am a bit confused of how to use one over the other and when to use them.