#!/usr/bin/env python # coding: utf-8 # # Basic exception handling # In[1]: class Calc: def Inverse(self, num): return 1/num try: cal = Calc() cal.Inverse(0) except Exception as err: print("An exception has occurred") # # Handling specific exceptions # ### The exception in below example will be caught by first except block # In[2]: 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) # ### The exception in below example will be caught by second except block # In[3]: 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) # # Raising an exception # In[4]: 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) # # The else and finally block # ### The else block # In[6]: bob = Student() try: bob.setAge(20) except Exception as error: print("An exception has occurred -", error) else: print("Age was assigned successfully!") # ### The finally block # In[7]: 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") # # User defined exceptions # In[8]: 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)