basic_exceptions.py - #some brief examples on how to use...

Info icon This preview shows pages 1–2. Sign up to view the full content.

#some brief examples on how to use exceptions def safe_divide(a ,b): try: #put code that could cause an exception in a try block c = a / b print('%f/%f = %f' % (a,b,c)) #except NameOfException except ZeroDivisionError: #inside the except block you put that you want to be run if an exception occurs #you should place the name of the exception that you are trying to handle next to the except keyword print("You can't divide by 0!") def safe_user_divide(): #you can have multiple exceptions to be checked for in a try block #there is on limit to how many except clauses we can have. try: a = int(input('Enter a number to be divided: ')) b = int(input('Enter a number to divide by: ')) c = a / b print('%f/%f = %f' % (a,b,c)) except ValueError: #this one will be entered if either a or b is not an integer print('You entered a non integer') except ZeroDivisionError: #this one will be entered if we try and divide by 0 print("You can't divide by 0!") def safe_read(file_name): try: f = open(file_name) print(f.read()) f.close() print(f.read()) #this will cause an error because the file is closed
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

Image of page 2
This is the end of the preview. Sign up to access the rest of the document.
  • Fall '07
  • Amenta
  • #by, #an, #be

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern