📅  最后修改于: 2023-12-03 15:04:09.570000             🧑  作者: Mango
Python has a built-in error handling mechanism that allows you to handle exceptions (errors) gracefully instead of stopping your program altogether. This mechanism is known as try-except.
Try-Except block lets you catch errors that may occur during runtime and take corrective actions to prevent the program from crashing.
try:
# code to be executed here
except ExceptionType:
# code to handle the exception
try
block contains the code that may raise an exceptionexcept
block contains the code to handle the exceptionExceptionType
specifies the type of exception to handle (optional)Let's see some examples of Try-Except block in action:
In this example, we'll catch the ZeroDivisionError
that may occur if we try to divide a number by zero:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Enter a number: 10
Enter another number: 0
Cannot divide by zero!
In this example, we'll catch the ValueError
that may occur if we enter an invalid input:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Enter a number: 10
Enter another number: abc
Invalid input!
In this example, we'll use the else
block to execute some code only if no exception occurs:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Result:", result)
finally:
print("Execution complete.")
Output:
Enter a number: 10
Enter another number: 2
Result: 5.0
Execution complete.
In this example, we'll use a loop to keep asking for input until the user enters valid input:
while True:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ValueError:
print("Invalid input! Try again.")
except ZeroDivisionError:
print("Cannot divide by zero! Try again.")
else:
print("Result:", result)
break
finally:
print("Attempt complete.")
Output:
Enter a number: 10
Enter another number: 0
Cannot divide by zero! Try again.
Attempt complete.
Enter a number: 10
Enter another number: abc
Invalid input! Try again.
Attempt complete.
Enter a number: 10
Enter another number: 2
Result: 5.0
Attempt complete.
In conclusion, Try-Except block is an essential tool in Python programming as it helps to prevent program crashing errors by handling exceptions gracefully. By following the examples shown above, you can implement Try-Except block into your code and better manage error handling in your programs.