FAQ Try-Except
Goal
Learn to use try-expect blocks to enhance the readability of the program, to avoid program crash, and to understand the error messages.
Introduction
In Python, try-except blocks are an exception handling mechanism. Exceptions allow a program to gracefully manage errors that occur during runtime without crashing. Try-except blocks allow users to insert codes to handle errors, to record errors, to display error messages, or to execute other programs.
Example
## try-except
try:
# Program segment potentially generates an erorr
risky_code()
except Exception as e:
# Display an error message
print('Error Msg:{}'.format(e))
Example 1: Design a busy_function
try:
import time
def busy_function(duration):
print('Busy function starting for {} seconds...'.format(duration))
start_time = time.time()
while time.time() - start_time < duration:
#Continue or keep busy
_ = 0
for i in range(10000):
_ += i
print("Busy function completed.")
# Allows busy_function to execute for 20 more seconds
busy_function(20)
except Exception as e:
# Displly an error massage
print('Error Msg:{}'.format(e))
Conclusion
Users can include import, def, or the main program into a try-except block to ensure that the program will not crash when an error occurs. In addition, error messages can be shown to flag the potential causes. Mastering try-except blocks can enhance the efficiency of the program debugging.