Exceptional Handling
When the following program is run an error is generated
1 2 3 | n = "w" n = int(n) print(n) |
With exceptional handling the program will run, fail gracefully but give the user information.
Copy the program into IDLE and run it entering a character ‘a’ and an integer ‘2’
1 2 3 4 5 6 7 8 | while True: try: n = input("Please enter an integer: ") n = int(n) break except ValueError: print("No valid integer! Please try again ...") print("Great, you successfully entered an integer!") |
The following program looks for a file that doesn’t exist. Rather than giving a messy red error message it gives information and fails gracefully. Try running it
Previous Lesson