Exception Handling

I LOVE DOING THIS :)

If at any point in the program an Error occurs, then the program should exit gracefully

Exceptions are raised when an external event occurs which in some way changes the normal flow of the program

How to Handle Exceptions

  • Put the unsafe code in Try: block

  • Put the fall-back code in Except: block

  • Put the final code in Finally: block

>>> try:
...    div = 1/0
...    print(div)
... except ZeroDivisionError as e:
...    print(e)
... finally:
...    print("in the final block")

Exceptions can also be raised if you want the code to behave within specific parameters

#!/opt/python3

while True:
	try:
		num = int(input())
		if num < 0:
			raise ValueError("Please enter positive number")
		else:
			print("user input: %d" % num)
	except ValueError as e:
		print(e)

User Defined Exceptions

Writing a sample program which detects the Disallow tag in the robots.txt and raises an User-Defined Exception

#!/opt/python2

class DisallowPresent(Exception):
	def __init__(self, path):
		self.path = path

	def invoke(self):
		return(self.path)

import urllib2

link = urllib2.urlopen("https://www.bbc.co.uk/robots.txt")

for line in link.readlines():
	try:
		if line.lower().find("disallow") != -1:

			print(line.strip())
			raise DisallowPresent(line.split(":")[1].strip())


	except DisallowPresent as e:
		print "Exceptions occured: " +e.path

Last updated