Handling exceptions in python

Previous
Next

Try with Multiple Exceptions:

  • One try block can have many instructions (logic) set.
  • Chance of getting different types of exceptions in different lines of code.
  • We can handle different types of exception by defining more than except block.
  • If you want to execute a special block of code for a special kind of error:

Task: Open File -> Write info -> Send in Network -> End

try :
    Opening File  (if not present)
    Writing info (read only file)
    Sending (connection lost)
    End
except  FileNotFoundError :
    Error : no file to open
except  SecurityError:
    Error : no write permissions
except  NetworkError :
    Error : no data connection

Division example with multiple execptions:

class Division:
    def main():
        try:
            print("Enter 2 numbers :")
            x = int(input())
            y = int(input())
            z = x/y
            print("Result :",z)

        except ValueError:
            print("Exception : Invalid input")

        except ZeroDivisionError:
            print("Exception : Denominator should not be zero")
        print("End")
        return

Division.main()
Previous
Next

Add Comment

Courses Enquiry Form