gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
give example for try catch in python
- User
give example for try catch in python
- Assistant
Here's an example of using try-except in Python:
try: num = int(input("Enter a number: ")) print("The number you entered is:", num) result = 100 / num print("The result is:", result) except ValueError: print("Error: You didn't enter a valid integer!") except ZeroDivisionError: print("Error: You can't divide by zero!") finally: print("Thank you for using this program!")In this example, the user is prompted to enter a number. If the user enters something that can't be converted to an integer (like a string or a float), a ValueError exception will be raised and the program will print an error message. If the user enters 0, a ZeroDivisionError will be raised when the program tries to divide by 0. Finally, the program will print a message thanking the user for using the program, regardless of whether an exception was raised or not.