Python
  • Getting Started
    • Input and Output
    • Variables
    • Data Types
    • Conditional Structures
      • Humidity Level
      • Financial Transactions
      • Fruit-Vending Machine
      • Magic While
      • FizzBuzz
    • Functions
      • Hashtag Generator
  • Data Structures
    • Lists
    • Dictionary
    • Set
    • Interpreter Expressions
  • OOPs
    • Classes and Objects
    • Exception Handling
      • Simple Calculator
  • System Programming
    • File Operations
    • Directory Navigation
    • Process Creation
    • Threads
Powered by GitBook
On this page
  • How to Handle Exceptions
  • User Defined Exceptions
  1. OOPs

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
PreviousClasses and ObjectsNextSimple Calculator

Last updated 2 years ago