Presentation is loading. Please wait.

Presentation is loading. Please wait.

Handling Errors Introduction to Computing Science and Programming I.

Similar presentations


Presentation on theme: "Handling Errors Introduction to Computing Science and Programming I."— Presentation transcript:

1 Handling Errors Introduction to Computing Science and Programming I

2 Exceptions When an error occurs while a program is running it is called an exception. When an error occurs while a program is running it is called an exception. If you know that an exception may occur in your program you can use the try – except structure to catch the error and prevent your program from crashing. If you know that an exception may occur in your program you can use the try – except structure to catch the error and prevent your program from crashing.

3 try – except structure try:codeblockexcept:codeblock If an error occurs while in the try codeblock, execution in that codeblock will immediately stop and the code in the except codeblock will be executed. If no error occurs, the code in the except block will be ignored. If an error occurs while in the try codeblock, execution in that codeblock will immediately stop and the code in the except codeblock will be executed. If no error occurs, the code in the except block will be ignored.

4 try – except structure m_str = raw_input("Enter your height (in metres): ") try: metres = float(m_str) feet = 39.37 * metres / 12 print "You are " + str(feet) + " feet tall." except: print "That wasn’t a number.“ If the user doesn’t enter a number they will see an error message. You can then add a while loop to keep prompting the user until they enter a number. If the user doesn’t enter a number they will see an error message. You can then add a while loop to keep prompting the user until they enter a number.

5 try – except structure got_height = False while not got_height: m_str = raw_input("Enter your height (in metres): ") try: metres = float(m_str) feet = 39.37 * metres / 12 print "You are " + str(feet) + " feet tall.“ got_height = True except: print "That wasn’t a number.“ When there’s an error in the float conversion execution will exit the try block before setting got_height to True. When there’s an error in the float conversion execution will exit the try block before setting got_height to True.


Download ppt "Handling Errors Introduction to Computing Science and Programming I."

Similar presentations


Ads by Google