class Calc:
def Inverse(self, num):
return 1/num
try:
cal = Calc()
cal.Inverse(0)
except Exception as err:
print("An exception has occurred")
An exception has occurred
try:
cal = Calc()
cal.Inverse(0)
except ZeroDivisionError as zeroDivideError:
print("A zero division exception has occurred. Exception message -", zeroDivideError)
except Exception as err:
print("An exception has occurred -", err)
A zero division exception has occurred. Exception message - division by zero
try:
cal = Calc("")
cal.Inverse(0)
except ZeroDivisionError as zeroDivideError:
print("A zero division exception has occurred. Exception message -", zeroDivideError)
except Exception as err:
print("An exception has occurred -", err)
An exception has occurred - object() takes no parameters
class Student:
def setAge(self, age):
if(age < 18):
raise Exception("Age can not be less than 18")
else:
self.age = age
alice = Student()
try:
alice.setAge(15)
except Exception as error:
print("An exception has occurred -", error)
An exception has occurred - Age can not be less than 18
bob = Student()
try:
bob.setAge(20)
except Exception as error:
print("An exception has occurred -", error)
else:
print("Age was assigned successfully!")
Age was assigned successfully!
bob = Student()
try:
bob.setAge(20)
except Exception as error:
print("An exception has occurred -", error)
else:
print("Age was assigned successfully!")
finally:
print("Finally block - This always gets executed")
Age was assigned successfully! Finally block - This always gets executed
class SalaryError(Exception):
def __init__(self, arg):
self.arg = arg
class Employee:
def setSalary(self, salary):
if(salary < 0):
raise SalaryError("Salary can't be less than 0")
else:
self.salary = salary
try:
chris = Employee()
chris.setSalary(-100)
except SalaryError as error:
print("Salary exception occurred - ", error)
Salary exception occurred - Salary can't be less than 0