Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save techsharif/fc2cdcc8e0b44d14ec8e9633e4cec186 to your computer and use it in GitHub Desktop.
Save techsharif/fc2cdcc8e0b44d14ec8e9633e4cec186 to your computer and use it in GitHub Desktop.
python_training_and_exercise_on_Exceptions

Exceptions

Sharif Chowhdury
Software Engineer ( Circle FinTech Ltd. )
techsharif.com

Errors

  • Syntax errors
  • Semantic errors
  • Logical errors

Try Except

Basic
try:
	1 / 0
except ZeroDivisionError:
	print("You cannot divide by zero!")
Worse practice
try:
	1 / 0
except:
	print("You cannot divide by zero!")
Exception Hierarchy ( Example )
  • BaseException
    • Exception
      • ArithmeticError
        • FloatingPointError
        • OverflowError
        • ZeroDivisionError
      • AssertionError
try:
	1 / 0
except ArithmeticError:
	print("You cannot divide by zero!")
Handling Multiple Exceptions raise
a = 5
b = 6


def divide_test(a,b):
	try:
		print(a / b)
	except TypeError:
		print("Please provide numbers")
	except ZeroDivisionError:
		print("You cannot divide by zero!")


divide_test(4,5)
divide_test(4,0)
divide_test(4,"asdf")
assert
Temperature = -1
assert (Temperature >= 0),"Colder than absolute zero!"
Custom Exception Classes
class StudentNumberError(Exception):
	def __init__(self):
		Exception.__init__(self,"Number of students should be non negetive integer") 

class Batch:
	def __init__(self, students):
		if type(students) == int and students >= 0:
			self.students = students
		else:
			raise StudentNumberError
Test 01
obj = Batch(5)
print(obj.students)
Test 02
obj = Batch(-1)
print(obj.students)
Test 03
try:
	obj = Batch(-1)
	print(obj.students)
except StudentNumberError:
	print("an error occur")
finaly
  • Execute at the end
my_dictionary = dict()
try:
	value = my_dictionary["d"]
except KeyError:
	print("A KeyError occurred!")
finally:
	print("The finally statement has executed!")
else
  • The else will only run if there are no errors raised.
test 01
my_dictionary = {"a":1, "b":2, "c":3}
try:
	value = my_dictionary["a"]
except KeyError:
	print("A KeyError occurred!")
else:
	print("No error occurred!")
Test 02


my_dictionary = {"a":1, "b":2, "c":3}
try:
	value = my_dictionary["d"]
except KeyError:
	print("A KeyError occurred!")
else:
	print("No error occurred!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment