basic_exceptions.py

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

• Notes
• 2

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

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

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

• 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.

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

• 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.

Dana University of Pennsylvania ‘17, Course Hero Intern

• 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.

Jill Tulane University ‘16, Course Hero Intern