Python中异常处理:10大常见异常及其处理实例
在Python编程中,异常处理是一种机制,用于在程序执行过程中遇到错误时进行适当的处理。以下是Python中10种常见的异常以及相应的处理实例:
ZeroDivisionError:当除数为零时引发。示例:
try:
division = 1 / 0
except ZeroDivisionError as e:
print(f"Error: {e}. Avoid dividing by zero.")
TypeError:当操作或函数应用于不合适的类型时引发。示例:
try:
int_string = "32"
float_number = int_string + ".5"
print(float_number)
except TypeError as e:
print(f"Error: {e}. Type conversion may be required.")
ValueError:当数据不符合预期格式时引发。示例:
try:
email = "invalid-email"
validate_email(email)
except ValueError as e:
print(f"Error: {e}. Email validation failed.")
KeyError:当试图访问字典中不存在的键时引发。示例:
try:
my_dict = {"name": "Alice", "age": 25}
print(my_dict["address"]))
except KeyError as e:
print(f"Error: {e}. Key 'address' not found in dictionary.")
IndexError:当尝试访问列表中的某个索引超出范围时引发。示例:
try:
my_list = [1, 2, 3]
print(my_list[4])
except IndexError as e:
print(f"Error: {e}. Index '4' is out of range for list.")
FileNotFoundError:当尝试打开一个不存在的文件时引发。示例:
try:
file_to_open = "nonexistent_file.txt"
with open(file_to_open, 'r') as f:
print(f.read())
except FileNotFoundError as e:
print(f"Error: {e}. File 'nonexistent_file.txt' not found.")
IOError:这是
FileNotFoundError
的父类,当文件操作遇到更广泛的错误时引发。示例:try:
file_to_open = "broken_file"
with open(file_to_open, 'r') as f:
print(f.read())
except IOError as e:
print(f"Error: {e}. File 'broken_file' could not be opened due to an error.")
SystemExit:在Python中,当调用
os.system()
或sys.exit()
时会引发。示例:try:
exit_message = "Program gracefully stopped."
os.system("echo " + exit_message)
sys.exit(0) # Normal exit, no error code
except SystemExit as e:
print(f"Error: {e}. Program was terminated via 'sys.exit()'.")
Timeout:当使用
time.sleep()
或其他可能导致阻塞的操作时,可能会遇到超时问题。示例:try:
time_to_wait = 5 # seconds
sleep(time_to_wait)
print("Action completed within the timeout.")
except TimeoutError as e:
print(f"Error: {e}. Action timed out after '{time_to_wait}' seconds.".format(time_to_wait)))
SyntaxError:当Python解析器遇到语法错误时,会引发此错误。示例:
try:
invalid_code = "print('Hello, World!')\ninvalid_line"
exec(invalid_code) # Raises SyntaxError
except SyntaxError as e:
print(f"Error: {e}. Invalid syntax found in code.".format(invalid_code)))
以上就是Python中常见异常及其处理的示例。在实际编程中,根据具体需求和场景进行异常处理是非常重要的。
还没有评论,来说两句吧...