try except expection
时间: 2023-10-25 14:10:16 浏览: 99
expection.vue
Try-except is a programming construct used in Python and other programming languages to handle errors or exceptions that may occur during the execution of a program.
A try-except block consists of two parts: the try block and the except block. The try block contains the code that may raise an exception, while the except block contains the code to handle the exception if it occurs.
Here is a basic example of try-except in Python:
```
try:
x = int(input("Enter a number: "))
y = 10 / x
print(y)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
```
In this example, the user is prompted to enter a number, which is then used to calculate 10 divided by that number. If the user enters 0, a ZeroDivisionError exception will be raised, and the program will print "Cannot divide by zero". If the user enters a non-numeric value, a ValueError exception will be raised, and the program will print "Invalid input".
阅读全文