网站首页> 文章专栏> 机器学习之Python(12): Python中try - except
num = 10 / 0
lst = [1, 2, 3]print(lst[3])
d = {'a': 1, 'b': 2}print(d['c'])
print(nonexistent_var)
print(1 + "2")
try: num = 10 + 5 print(num)except: print("发生异常")
try: result = 10 / 0except ZeroDivisionError: print("除数不能为零")
try: num = int("abc") result = 10 / numexcept Exception as e: print(f"发生异常: {e}")
try: num = input("请输入一个数字: ") num = int(num) result = 10 / num print(f"结果是: {result}")except ValueError: print("输入的不是有效的数字")except ZeroDivisionError: print("除数不能为零")
try: # 可能会抛出异常的代码 passexcept SomeExceptionType: # 当try块中抛出SomeExceptionType类型的异常时执行的代码 passelse: # 当try块中的代码没有抛出异常时执行的代码 pass
try: file_name = "example.txt" with open(file_name, 'r') as file: content = file.read()except FileNotFoundError: print(f"文件{file_name}不存在")else: print(f"文件内容为:\n{content}")
try: # 可能会抛出异常的代码 passexcept SomeExceptionType: # 当try块中抛出SomeExceptionType类型的异常时执行的代码 passfinally: # 无论是否发生异常都会执行的代码 pass
file = Nonetry: file = open("test.txt", "r") content = file.read() print(content)except FileNotFoundError: print("文件不存在")finally: if file: file.close()
def read_file(): file = None try: file = open("test.txt", "r") content = file.read() return content except FileNotFoundError: print("文件不存在") finally: if file: file.close()result = read_file()print(result)
import pymysqldef query_database(): connection = None try: connection = pymysql.connect(host='localhost', user='your_username', password='your_password', database='your_database', port=3306, charset='utf8mb4') cursor = connection.cursor() sql = "SELECT * FROM your_table" cursor.execute(sql) results = cursor.fetchall() for row in results: print(row) except pymysql.Error as e: print(f"发生错误:{e}") finally: if connection: connection.close()query_database()
try: with open('test.txt', 'r') as file: content = file.read() print(content)except FileNotFoundError: print("文件不存在")except PermissionError: print("权限不足,无法读取文件")
try: with open('output.txt', 'w') as file: file.write("这是写入的内容")except PermissionError: print("权限不足,无法写入文件")except Exception as e: print(f"写入文件时发生错误: {e}")
import requeststry: response = requests.get('https://example.com', timeout=5) response.raise_for_status() # 检查HTTP状态码,如果不是200,会引发HTTPError异常 print(response.text)except requests.Timeout: print("请求超时")except requests.HTTPError as e: print(f"HTTP错误: {e}")except requests.ConnectionError: print("连接错误")except requests.RequestException as e: print(f"请求发生异常: {e}")
try: num = input("请输入一个整数: ") num = int(num) result = 10 / num print(f"结果是: {result}")except ValueError: print("输入的不是有效的整数")except ZeroDivisionError: print("除数不能为零")
import pymysqltry: connection = pymysql.connect(host='localhost', user='your_username', password='your_password', database='your_database', port=3306, charset='utf8mb4') cursor = connection.cursor() sql = "SELECT * FROM your_table" cursor.execute(sql) results = cursor.fetchall() for row in results: print(row)except pymysql.Error as e: print(f"数据库操作发生错误: {e}")finally: if connection: connection.close()
try: result = 10 / int(input("请输入一个数字: ")) print(f"结果是: {result}")except: print("出现了一些问题")
import osfile_name = "test.txt"if os.path.exists(file_name): with open(file_name, 'r') as file: content = file.read() print(content)else: print(f"文件{file_name}不存在")
try: with open("test.txt", 'r') as file: content = file.read() print(content)except FileNotFoundError: print("文件不存在")
在这个场景中,使用os.path.exists进行文件是否存在的判断是更合适的做法,它的逻辑清晰,性能也更好。而使用异常处理虽然也能达到目的,但在文件存在的正常情况下,异常处理的开销是不必要的。只有当我们无法预先判断某个操作是否会出现异常,或者异常情况确实是不可预见的意外时,才应该使用异常处理机制 。比如在进行网络请求时,由于网络的不确定性,我们很难提前判断请求是否会成功,这时使用异常处理来捕获可能出现的异常就是合理的。