偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

20個(gè)改善編碼的Python異常處理技巧,讓你的代碼更高效

開發(fā)
異常處理是寫好代碼的一個(gè)重要的方面,雖然許多開發(fā)人員都熟悉基本的try-except塊,但是有很多更深入的知識(shí)可以使異常處理更高效、更可讀和更python化。所以本文將介紹關(guān)于Python異常的20個(gè)可以顯著改善編碼的Python異常處理技巧,這些技巧可以讓你熟練的掌握Python的異常處理。

異常處理是寫好代碼的一個(gè)重要的方面,雖然許多開發(fā)人員都熟悉基本的try-except塊,但是有很多更深入的知識(shí)可以使異常處理更高效、更可讀和更python化。所以本文將介紹關(guān)于Python異常的20個(gè)可以顯著改善編碼的Python異常處理技巧,這些技巧可以讓你熟練的掌握Python的異常處理。

Python中的異常是在程序執(zhí)行期間發(fā)生的破壞了程序指令的正常流程的事件。與其他編程語(yǔ)言一樣,Python使用異常來代表錯(cuò)誤發(fā)生的信號(hào),程序可以做出反應(yīng),并恢復(fù)或通知用戶產(chǎn)生的問題。

1、最簡(jiǎn)單的異常處理

我們都知道最簡(jiǎn)單的異常處理如下:

try:
    # Your code here
 except IOError:
    # Handle I/O errors
 except Exception as e:
    # Handle other exceptions
 finally:
    # Cleanup, runs no matter what

異常是按層次結(jié)構(gòu)組織的,如果發(fā)生了IOError會(huì)執(zhí)行IOError的except代碼,剩下的異常則交由Exception處理。理解這個(gè)層次結(jié)構(gòu)可以根據(jù)需要更廣泛或更具體地捕獲錯(cuò)誤。

使用finally子句確保執(zhí)行清理操作,而不管是否發(fā)生異常。它非常適合關(guān)閉文件或釋放資源。

2、自定義異常

創(chuàng)建自定義異??梢允勾a更具可讀性和可維護(hù)性,可以清楚地表示特定的錯(cuò)誤條件。

class MyCustomError(Exception):
    pass
 
 try:
    raise MyCustomError("A specific error occurred")
 except MyCustomError as e:
    print(e)

3、Else in Try-Except

如果沒有引發(fā)異常,則try-except塊中的else子句將運(yùn)行。這是其他語(yǔ)言沒有的

try:
    # Attempt operation
 except Exception:
    # Handle error
 else:
    # Executes if no exceptions

4、AS關(guān)鍵字

在捕獲異常時(shí),可以使用as關(guān)鍵字將異常分配給一個(gè)變量,這樣可以顯示詳細(xì)信息并使調(diào)試更容易。

try:
    # Some operation
 except Exception as e:
    print(f"Error: {e}")

5、捕獲多個(gè)異常

元組可用于在一行中捕獲多種異常類型,從而簡(jiǎn)化錯(cuò)誤處理代碼。

try:
    # Risky operation
 except (TypeError, ValueError) as e:
    # Handle both exceptions

6、異常觸發(fā)另外的異常

Python允許在使用from保持原始回溯的同時(shí)觸發(fā)新的異常,從而幫助調(diào)試復(fù)雜的場(chǎng)景。

try:
    # Some operation
 except Exception as original_error:
    raise RuntimeError("Something bad happened") from original_error

這種方法有好有壞,所以如果不熟悉的話建議還是不要用。

7、忽略異常

使用contextlib.suppress()函數(shù),可以優(yōu)雅地忽略特定的異常,從而使代碼更清晰、更易讀。

from contextlib import suppress
 
 with suppress(FileNotFoundError):
    # Operation that might not find a file

8、使用斷言

如果不滿足條件,可以使用斷言拋出異常。但是要謹(jǐn)慎使用它們,因?yàn)樗鼈兛梢酝ㄟ^執(zhí)行時(shí)的優(yōu)化標(biāo)志被禁用。

assert condition, "Condition was not met"

assert 斷言會(huì)拋出AssertionError,可以在except中直接捕獲

9、格式化異常信息

利用Traceback模塊打印詳細(xì)的異常信息,這樣可以顯示完整的錯(cuò)誤來幫助調(diào)試。

import traceback
 
 try:
    raise ValueError("An error occurred")
 except:
    traceback.print_exc() # Print exception information to stderr

10、使用warnings模塊發(fā)出非致命警報(bào)

warnings模塊發(fā)出是警告而不是異常。如果希望在不停止程序執(zhí)行的情況下提醒用戶或開發(fā)人員潛在問題時(shí),它非常有用。

import warnings
 
 warnings.warn("This is a warning message", UserWarning)

11、忽略異常

suppress函數(shù)被用來忽略特定的異常。contextlib可以確保資源在使用后得到適當(dāng)?shù)那謇怼?/span>

from contextlManaging Resources: Illustrates creating context managers for resource management, ensuring resources are properly cleaned up after use. The suppress function is shown to ignore specific exceptions.ib import contextmanager, suppress
 
 @contextmanager
 def managed_resource():
    try:
        resource = "Resource"
        yield resource
    finally:
        print("Resource cleanup")
 
 with managed_resource() as res:
    print(res)
 
 with suppress(FileNotFoundError):
    open('non_existent_file.txt', 'r') # Suppresses the FileNotFoundError

12、創(chuàng)建處理異常的包裝器函數(shù)

functools模塊可以創(chuàng)建一個(gè)裝飾器來包裝用于集中異常處理的函數(shù),從而簡(jiǎn)化跨多個(gè)函數(shù)的錯(cuò)誤管理。

from functools import wraps
 
 def exception_handler(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(f"Handled exception: {e}")
            return None
    return wrapper
 
 @exception_handler
 def risky_function():
    raise ValueError("Something went wrong")
 
 risky_function()

13、訪問異常相關(guān)的屬性和函數(shù)

使用sys.exc_info()可以獲取有關(guān)當(dāng)前異常的詳細(xì)信息,這對(duì)于進(jìn)一步記錄或處理錯(cuò)誤細(xì)節(jié)很有用。

import sys
 
 try:
    raise TypeError("An error occurred")
 except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print(exc_type, exc_value)

14、分析當(dāng)前異常上下文

利用inspect模塊分析當(dāng)前異常上下文,這對(duì)于復(fù)雜的錯(cuò)誤處理場(chǎng)景特別有用。

import inspect
 
 def current_exception():
    for frame in inspect.trace():
        if frame[3] == 'risky_function':
            return frame[0].f_locals.get('e')
 
 try:
    risky_function()
 except Exception as e:
    print(current_exception())

15、創(chuàng)建動(dòng)態(tài)異常類

types模塊可以動(dòng)態(tài)創(chuàng)建異常類。這對(duì)于基于運(yùn)行時(shí)條件動(dòng)態(tài)生成自定義異常非常有用。

import types
 
 DynamicException = types.new_class('DynamicException', (Exception,))
 raise DynamicException("A dynamically created exception")

16、訪問所有內(nèi)置異常

builtins可以列出Python中可用的所有內(nèi)置異常,幫助我們了解層次結(jié)構(gòu)和各種異常。

import builtins
 
 for name in dir(builtins):
    obj = getattr(builtins, name)
    if isinstance(obj, type) and issubclass(obj, BaseException):
        print(name)

17、自定義異常的字符串表示形式

可以通過覆蓋__str__和__repr__方法來演示自定義異常,獲得更多信息豐富的錯(cuò)誤消息。

class MyException(Exception):
    def __str__(self):
        return "This is a custom message for MyException"
 
    def __repr__(self):
        return "MyException()"
 
 raise MyException

18、創(chuàng)建不被except Exception捕獲的異常

常規(guī)except的Exception塊會(huì)捕獲從BaseException派生的異常,比如非常嚴(yán)重的錯(cuò)誤我們可以派生字BaseException。

class MyCriticalError(BaseException):
    pass
 
 try:
    raise MyCriticalError("A critical error")
 except Exception as e:
    print("This will not catch MyCriticalError")

19、優(yōu)雅的處理用戶和系統(tǒng)中斷

捕獲KeyboardInterrupt和SystemExit異常,以優(yōu)雅地處理用戶或系統(tǒng)啟動(dòng)的關(guān)機(jī)。

import sys
 
 try:
    while True:
        continue
 except KeyboardInterrupt:
    print("User interrupted the process")
    sys.exit(0)

20、生成器的資源回收

GeneratorExit表示生成器執(zhí)行時(shí)產(chǎn)生了異常,捕獲它可以在關(guān)閉生成器時(shí)進(jìn)行清理操作。

def my_generator():
    try:
        yield "Hello"
    except GeneratorExit:
        print("Generator closing")
        raise
 
 gen = my_generator()
 next(gen)
 gen.close()

總結(jié)

Python異??梢詷O大地增強(qiáng)代碼的健壯性和清晰度。本文整理的20個(gè)異常處理代碼示例可以幫助你充分利用Python的錯(cuò)誤處理能力,顯著改善代碼的異常處理能力。

責(zé)任編輯:華軒 來源: DeepHub IMBA
相關(guān)推薦

2019-11-25 10:20:54

CSS代碼javascript

2024-06-24 00:05:00

Python代碼

2019-04-29 08:31:25

PythonPandas數(shù)據(jù)

2011-08-29 09:33:48

2023-07-26 07:41:53

Python線程狀態(tài)

2019-01-29 15:40:06

云應(yīng)用開發(fā)云環(huán)境

2018-06-20 11:00:06

云應(yīng)用開發(fā)PaaS

2024-08-19 00:35:00

Pythondict遍歷列表推導(dǎo)式

2024-09-06 17:32:55

字符串Python

2014-08-11 12:54:27

構(gòu)建模塊代碼審查編程

2024-08-02 17:23:12

2023-11-07 08:25:34

API接口參數(shù)驗(yàn)證

2015-03-16 16:56:54

開發(fā)技巧應(yīng)用孤島PaaS

2010-12-23 15:55:00

上網(wǎng)行為管理

2023-11-16 08:55:14

CSS前端

2024-01-08 17:09:07

Python解釋器CPython

2023-07-30 17:10:32

TypeScript開發(fā)

2020-05-07 17:03:49

Python編碼開發(fā)

2025-04-21 17:55:25

2019-10-28 09:53:42

Java開發(fā)結(jié)構(gòu)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)