」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Python 中的錯誤處理與日誌記錄

Python 中的錯誤處理與日誌記錄

發佈於2024-08-14
瀏覽:822

Writing software is an activity far from perfect. From ideation to production, errors can appear, and in some cases, failure can occur deliberately. This is why understanding error handling and logging in your primary programming language is a critical skill to master.

Errors can happen, and situations can arise, but how you respond—with preparation and information on the error—will get you out of the situation as quickly as possible.

In this article, we will learn about error handling and logging in Python. We will primarily explore exceptions and how to use Python’s logging package to write various types of logs.

If you are interested in more content covering topics like this, subscribe to my newsletter for regular updates on software programming, architecture, and tech-related insights.

Exceptions in Python

As in many other programming languages, Python has the capability to raise exceptions when errors occur. In programming, an exception is an event that occurs during the execution of a program, disrupting the normal flow of instructions.

In Python, exceptions are errors detected during execution. When an exception occurs, Python stops running the code and looks for a special block of code (a try/except block) to handle the error.

Here are some common exceptions that can occur in a Python program:

  • ZeroDivisionError: Occurs when attempting to divide a number by zero.

  • FileNotFoundError: Occurs when trying to open a file that doesn't exist.

  • ValueError: Occurs when trying to convert a string into an integer when the string does not represent a number.

  • IndexError: Occurs when trying to retrieve an element from a list with a non-existing index.

There are many more exceptions, and Python gives you the ability to create your own exceptions if you need custom behavior. This is a feature we will explore later in the article.

To handle Python exceptions, you need to catch them. Catching exceptions requires a simple syntax known as try/except. Let's explore this.

Try/Except

The try/except block is used to handle exceptions. Code that might raise an exception is placed in the try block, and if an exception occurs, the except block is executed. Here is the syntax of try/except in a code block:

try:
    # Code that might raise an exception
    pass
except ExceptionType as e:
    # Code to handle the exception
    pass

The code that could potentially fail is put inside the try block. If an issue arises, the program’s execution will enter the except block.

Here is a flowchart that illustrates how try/except works:

Error Handling and Logging in Python

Let’s see how we can handle a division by zero with this approach:

# Handling division by zero
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
# The code will continue its execution

There are also additional blocks in the try/except syntax, such as else and finally:

try:
    # Code that might raise an exception
    pass
except ExceptionType as e:
    # Code to handle the exception
    pass
else:
    # Code to run if no exception is raised
    pass
finally:
    # Code that always runs, regardless of whether an exception was raised or not
    pass

These blocks are optional but serve specific purposes:

  • else Block (Optional): Contains code that runs if no exceptions are raised in the try block. It is useful for code that should only run when the try block is successful.

  • finally Block (Optional): Contains code that always runs, regardless of whether an exception was raised or not. This is typically used for cleanup actions, such as closing files or releasing resources.

Here is an example where we handle the closing of a file in finally in case of an error:

try:
    # Open the file
    file = open('example.txt', 'r')

    # Read from the file
    content = file.read()

    # Print file content (this will only execute if no exceptions are raised)
    print(content)
except FileNotFoundError as e:
    # Handle the specific exception
    print(f"Error: {e}")
except Exception as e:
    # Handle any other exceptions
    print(f"An unexpected error occurred: {e}")
else:
    # Code that runs if no exception was raised in the try block
    print("File read successfully.")
finally:
    # Ensure the file is closed, regardless of whether an exception was raised
    try:
        file.close()
        print("File closed.")
    except:
        # Handle the case where file was never opened (e.g., if open() failed)
        print("File was not opened or already closed.")

Disclaimer: The example above demonstrates file handling using try/except/finally to ensure the file is properly closed even if an error occurs. However, this approach is not ideal for everyday file operations. In practice, it is recommended to use the with statement for file handling in Python. The with statement automatically manages file opening and closing, ensuring that the file is properly closed after its suite finishes, even if an exception occurs.

This is how the try/except works. Now, there might be some confusion with if/else. When should you use try/except, and when should you use if/else?

What’s the difference between try/except and if/else? Use if/else when you want to check conditions that you can predict and handle before they cause errors, and use try/except to catch and manage exceptions that occur during code execution, particularly for errors you can’t easily anticipate.

In the case below, if/else won’t work properly:

filename = 'non_existent_file.txt'

if filename:  # This only checks if filename is not empty, not if the file exists
    # The following line will raise an exception if the file doesn't exist
    content = open(filename, 'r').read()  # This will crash if the file does not exist
    if content:
        print("File content exists:")
        print(content)
    else:
        print("File is empty.")
else:
    print("Filename is invalid.")

Here is a better solution with try/except:

filename = 'non_existent_file.txt'

try:
    content = open(filename, 'r').read()
    if content:
        print("File content exists:")
        print(content)
    else:
        print("File is empty.")
except FileNotFoundError:
    print("Error: File not found.")

In the solution above, the code attempts to open and read a file, checking if its content exists and printing it if present. If the file does not exist, it catches the FileNotFoundError and prints an error message, preventing the program from crashing.

As mentioned earlier in the article, Python allows for custom exceptions. Let’s learn more about it.

Creating Custom Exceptions in Python

In Python, you can define your own exceptions to handle specific error conditions in a more granular way. Custom exceptions are particularly useful in complex applications, such as fintech, where you may need to enforce business rules or handle specific error cases uniquely.

For example, in a fintech application, you might have a scenario where a wallet’s balance is checked against certain criteria. You may want to raise an exception if a wallet’s balance is not sufficient or does not conform to specific rules. Here’s how you can create and use a custom exception for this purpose:

# Define a custom exception
class WalletBalanceError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

# Function that checks wallet balance
def check_wallet_balance(wallet_balance, required_balance):
    if wallet_balance 



In this example, we define a custom exception WalletBalanceError to handle cases where a wallet’s balance does not meet the required criteria. The check_wallet_balance function raises this exception if the wallet’s balance is insufficient, providing a clear and specific error message.

Custom exceptions in Python help make the code more readable and maintainable by clearly defining specific error conditions and handling them in a structured manner.

Now that we know how to handle errors in Python, it’s time to understand what to do when these errors occur. There are many strategies, but keeping a log of these errors can help identify issues later and correct them. In the next section of this article, we will explore logging.

Logging in Python

Logging helps developers track errors, events, or any runtime information in an application or program. Logging is an important and crucial aspect of software engineering as it has the ability to record everything that goes right or wrong in a post-development application. Logging is one of the most important pillars of monitoring.

Python provides a built-in module that can be used for logging

purposes. To use this module, the first thing to do is to import it.

import logging

Then, configure the logger using the basicConfig method. You need to pass parameters to it, such as the log level, the format of the message, and the output file to save the log.

import logging

# Set up the basic configuration for logging
logging.basicConfig(filename='app.log', level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Log messages of various severity levels
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

In the example above, logs will be written to a file called app.log. The log message format includes the timestamp, logger name, log level, and the actual message.

Python logging has different log levels that indicate the severity of an event or message. These log levels allow you to categorize and filter messages based on their importance. Here’s a breakdown of the common log levels in Python:

Log Levels

  1. DEBUG: Detailed information, typically of interest only when diagnosing problems. Used for debugging purposes during development.

  2. INFO: Confirmation that things are working as expected. This is the level you would use for normal operations and informational messages.

  3. WARNING: An indication that something unexpected happened, or indicative of some problem in the near future (e.g., "disk space low"). The software is still working as expected.

  4. ERROR: Due to a more serious problem, the software has not been able to perform some function. An error indicates a significant issue that needs attention.

  5. CRITICAL: A very serious error, indicating that the program itself may be unable to continue running. Critical errors often represent severe problems that require immediate action.

The logging module allows you to control which messages are recorded by setting the logging level. Only messages that are equal to or more severe than the set level will be logged. The default level is WARNING, meaning only WARNING, ERROR, and CRITICAL messages are logged unless you change the logging configuration.

In the code example above, we set the logging level to DEBUG, which means all log messages (DEBUG, INFO, WARNING, ERROR, and CRITICAL) will be recorded in the app.log file.

You can also create custom loggers, which give you more control over how messages are logged. Custom loggers allow you to set up multiple loggers with different configurations, such as different log levels, formats, or output destinations. This is particularly useful in larger applications where you need to separate logs for different modules or components.

Here’s how you can create and use a custom logger:

import logging

# Create a custom logger
logger = logging.getLogger('my_custom_logger')

# Set the log level for the custom logger
logger.setLevel(logging.DEBUG)

# Create a file handler to write logs to a file
file_handler = logging.FileHandler('custom.log')

# Create a console handler to output logs to the console
console_handler = logging.StreamHandler()

# Set log levels for the handlers
file_handler.setLevel(logging.ERROR)
console_handler.setLevel(logging.DEBUG)

# Create a formatter for log messages
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Add the formatter to the handlers
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# Add the handlers to the logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)

# Log messages using the custom logger
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

In this example, we create a custom logger named my_custom_logger. This logger writes ERROR and more severe messages to a file called custom.log, while DEBUG and more severe messages are output to the console. By customizing the loggers, you can tailor the logging behavior to fit the specific needs of your application.

Real-world Example: Logging in a Web Application

In a web application, logging plays a critical role in monitoring and maintaining the system’s health. For example, in a Flask web application, you might use logging to track incoming requests, errors, and performance metrics.

Here’s a basic example of how you can use logging in a Flask application:

from flask import Flask, request
import logging

app = Flask(__name__)

# Set up the basic configuration for logging
logging.basicConfig(filename='webapp.log', level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

@app.route('/')
def index():
    app.logger.info('Index page accessed')
    return 'Welcome to the Flask Web Application!'

@app.route('/error')
def error():
    app.logger.error('Error page accessed')
    raise ValueError('This is a simulated error')

if __name__ == '__main__':
    app.run(debug=True)

In this Flask application, we configure logging to write logs to a file named webapp.log. Each time the index page is accessed, an informational log message is recorded. If the error page is accessed, an error log message is recorded, and a simulated error is raised.

By implementing logging in your web application, you can gain insights into user activity, system errors, and performance issues. This information is invaluable for debugging, troubleshooting, and optimizing the application.

Conclusion

Error handling and logging are essential aspects of software development, ensuring that applications run smoothly and that any issues are quickly identified and resolved.

In this article, we explored exceptions in Python, including how to handle them using try/except, and the importance of logging for tracking errors and events. We also discussed how to create custom exceptions and custom loggers to suit specific application needs.

By mastering error handling and logging, you’ll be better equipped to build robust and maintainable software that can gracefully handle unexpected situations and provide valuable insights into its operation.

If you enjoyed this article, consider subscribing to my newsletter so you don't miss out on future updates.

Your feedback is valuable! If you have any suggestions, critiques, or questions, please leave a comment below.

版本聲明 本文轉載於:https://dev.to/koladev/error-handling-and-logging-in-python-mi1?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 網站 HTML 程式碼
    網站 HTML 程式碼
    我一直在嘗試建立一個與航空公司相關的網站。我只是想確認我是否可以使用人工智慧生成程式碼來產生整個網站。 HTML 網站是否相容於博客,或者我應該使用 JavaScript?這是我用作演示的程式碼。 <!DOCTYPE html> <html lang="en">[](url...
    程式設計 發佈於2024-11-05
  • 像程式設計師一樣思考:學習 Java 基礎知識
    像程式設計師一樣思考:學習 Java 基礎知識
    本文介紹了 Java 程式設計的基本概念和結構。它首先介紹了變數和資料類型,然後討論了操作符和表達式,以及控制流程。其次,它解釋了方法和類,然後介紹了輸入和輸出操作。最後,本文透過一個工資計算器的實際範例展示了這些概念的應用。 像程式設計師一樣思考:掌握Java 基礎1. 變數與資料型別 ]Java...
    程式設計 發佈於2024-11-05
  • PHP GD 可以比較兩個影像的相似性嗎?
    PHP GD 可以比較兩個影像的相似性嗎?
    PHP GD 可以確定兩個影像的相似度嗎? 正在考慮的問題詢問是否可以使用以下命令確定兩個圖像是否相同PHP GD 通過比較它們的差異。這需要獲取兩個影像之間的差異並確定它是否完全由白色(或任何統一的顏色)組成。 根據所提供的答案,雜湊函數(如其他回應所建議的)不適用於此情境。比較必須涉及圖像內容而...
    程式設計 發佈於2024-11-05
  • 使用這些鍵編寫進階測試(JavaScript 中的測試需求)
    使用這些鍵編寫進階測試(JavaScript 中的測試需求)
    在本文中,您將學習每個高級開發人員都應該了解的 12 個測試最佳實踐。您將看到 Kent Beck 的文章“Test Desiderata”的真實 JavaScript 範例,因為他的文章是用 Ruby 編寫的。 這些屬性旨在幫助您編寫更好的測試。了解它們還可以幫助您在下一次工作面試中取得好成績。...
    程式設計 發佈於2024-11-05
  • 透過將 matlab/octave 演算法移植到 C 來實現 AEC 的最佳解決方案
    透過將 matlab/octave 演算法移植到 C 來實現 AEC 的最佳解決方案
    完畢!對自己有點印象。 我們的產品需要迴聲消除功能,確定了三種可能的技術方案, 1)利用MCU偵測audio out和audio in的音訊訊號,編寫演算法計算兩側聲音訊號的強度,根據audio out和audio in的強弱在兩個通道之間進行可選的切換,實現半雙工通話效果,但現在市面上都是全雙工...
    程式設計 發佈於2024-11-05
  • 逐步建立網頁:探索 HTML 中的結構和元素
    逐步建立網頁:探索 HTML 中的結構和元素
    ?今天標誌著我軟體開發之旅的關鍵一步! ?我編寫了第一行程式碼,深入研究了 HTML 的本質。涵蓋的元素和標籤。昨天,我探索了建立網站的拳擊技術,今天我透過創建頁眉、頁腳和內容區域等部分將其付諸實踐。我還添加了各種 HTML 元素,包括圖像元素和連結元素,甚至嘗試在單頁網站上進行內部連結。看到這些部...
    程式設計 發佈於2024-11-05
  • 專案創意不一定是獨特的:原因如下
    專案創意不一定是獨特的:原因如下
    在創新領域,存在一個常見的誤解,即專案創意需要具有開創性或完全獨特才有價值。然而,事實並非如此。我們今天使用的許多成功產品與其競爭對手共享一組核心功能。讓他們與眾不同的不一定是想法,而是他們如何執行它、適應用戶需求以及在關鍵領域進行創新。 通訊應用案例:相似但不同 讓我們考慮一下 ...
    程式設計 發佈於2024-11-05
  • HackTheBox - Writeup 社論 [已退休]
    HackTheBox - Writeup 社論 [已退休]
    Neste writeup iremos explorar uma máquina easy linux chamada Editorial. Esta máquina explora as seguintes vulnerabilidades e técnicas de exploração: S...
    程式設計 發佈於2024-11-05
  • 強大的 JavaScript 技術可提升您的編碼技能
    強大的 JavaScript 技術可提升您的編碼技能
    JavaScript is constantly evolving, and mastering the language is key to writing cleaner and more efficient code. ?✨ Whether you’re just getting starte...
    程式設計 發佈於2024-11-05
  • 如何在 ReactJS 中建立可重複使用的 Button 元件
    如何在 ReactJS 中建立可重複使用的 Button 元件
    按鈕無疑是任何 React 應用程式中重要的 UI 元件,按鈕可能用於提交表單或開啟新頁面等場景。您可以在 React.js 中建立可重複使用的按鈕元件,您可以在應用程式的不同部分中使用它們。因此,維護您的應用程式將變得更加簡單,並且您的程式碼將保持 DRY(不要重複自己)。 您必須先在元件資料夾...
    程式設計 發佈於2024-11-05
  • 如何在 Apache HttpClient 4 中實作搶佔式基本驗證?
    如何在 Apache HttpClient 4 中實作搶佔式基本驗證?
    使用Apache HttpClient 4 簡化搶佔式基本驗證雖然Apache HttpClient 4 已經取代了早期版本中的搶佔式驗證方法,但它提供了替代方法以實現相同的功能。對於尋求直接搶佔式基本驗證方法的開發人員,本文探討了一種簡化方法。 為了避免向每個請求手動新增 BasicHttpCon...
    程式設計 發佈於2024-11-05
  • 例外處理
    例外處理
    異常是運行時發生的錯誤。 Java 中的異常處理子系統可讓您以結構化和受控的方式處理錯誤。 Java為異常處理提供了易於使用且靈活的支援。 主要優點是錯誤處理程式碼的自動化,以前必須手動完成。 在舊語言中,需要手動檢查方法傳回的錯誤碼,既繁瑣又容易出錯。 異常處理透過在發生錯誤時自動執行...
    程式設計 發佈於2024-11-05
  • 如何在不使用「dangerouslySetInnerHTML」的情況下安全地在 React 中渲染原始 HTML?
    如何在不使用「dangerouslySetInnerHTML」的情況下安全地在 React 中渲染原始 HTML?
    使用更安全的方法在React 中渲染原始HTML在React 中,您現在可以使用更安全的方法來渲染原始HTML ,避免使用危險的SetInnerHTML 。這裡有四個選項:1。 Unicode 編碼使用Unicode 字元表示UTF-8 編碼檔案中的HTML 實體:<div>{`Firs...
    程式設計 發佈於2024-11-05
  • PHP 死了嗎?不,它正在蓬勃發展
    PHP 死了嗎?不,它正在蓬勃發展
    PHP 是一種不斷受到批評但仍在蓬勃發展的程式語言。 使用率:根據 W3Techs 的數據,截至 2024 年 8 月,全球 75.9% 的網站仍在使用 PHP,其中 43% 的網站基於 WordPress。使用PHP作為開發語言的主流網站中,超過70%包括Facebook、微軟、維基百科、Moz...
    程式設計 發佈於2024-11-05
  • PgQueuer:將 PostgreSQL 轉變為強大的作業佇列
    PgQueuer:將 PostgreSQL 轉變為強大的作業佇列
    PgQueuer 簡介:使用 PostgreSQL 實現高效能作業佇列 社區開發者您好! 我很高興分享一個項目,我相信該項目可以顯著簡化開發人員在使用 PostgreSQL 資料庫時處理作業佇列的方式。 PgQueuer,這是一個 Python 函式庫,旨在利用 PostgreS...
    程式設計 發佈於2024-11-05

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3