Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Python] use Try/Except in python

Posted on July 30, 2023 By nim No Comments on [Python] use Try/Except in python

Contents

Toggle
  • 1) Introduce try / except
  • 2) Use else finally in python
  • 3) How to find out the value exception on production

1) Introduce try / except

try:
  # Code that might cause an error
  x = int(input("Please enter a number: "))
  y = 1/x
  print(y)
except ValueError:
  # Handle ValueError exception
  print("Error: You must enter a valid number.")
except ZeroDivisionError:
  # Handle ZeroDivisionError exception
  print("Error: Cannot divide by zero.")
except:
  # Handle all other exceptions
  print("Unknown error occurred.")

The try block contains code that might cause an exception. If an exception occurs in the try block, Python will jump to the except block that matches the exception.

We have three except blocks to handle different exception types:

  • ValueError will be triggered if int() fails to convert the input to a number
  • ZeroDivisionError will occur if x is 0
  • The blanket except will catch any other exceptions not caught above

The advantage of try-except is that we can gracefully handle errors and continue program execution instead of crashing. We can also print custom error messages for the user.

To summarize:

  • Put risky code in try block
  • Catch anticipated exceptions in except blocks
  • Print error messages to notify user
  • Use except: to catch general errors
  • Program continues despite exceptions

This allows our program to continue running instead of terminating on an error.

2) Use else finally in python

try:
  x = int(input("Please enter a number: "))
  y = 1/x
except ValueError:
  print("Error: You must enter a valid number.")
except ZeroDivisionError:
  print("Error: Cannot divide by zero.")  
else:
  print(f"1/{x} is {y}") # Executes if no exceptions
finally:
  print("Executing finally block")

The else block executes only if no exceptions occur in the try block. This is useful for code that should run if everything succeeded.

The finally block always executes after the try and except blocks, even if an exception occurred. This is useful for cleanup code like closing files or network connections.

3) How to find out the value exception on production

There are a few good ways to get exception details when running an application in production:

  1. Log exceptions to file
import logging

try:
  # risky code 
except Exception as e: 
  logging.error(e, exc_info=True)
Python

Post navigation

Previous Post: [DevSecOps] Scan Terraform
Next Post: [Python] Look into “for else”

More Related Articles

[Python] what mean if __name__==”__main__”: Python
[Python] OOP Python
[Python] Look into FastAPI to contribute backend by Python Python
[Python] The eval() function automatically calculates a string Python
[Python] Look into “for else” Python
[Python] Python connects MongoDB Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Upload File] How to upload large files and download them using curl. July 23, 2025
  • [Argo Workflow] Create an access token for Argo Workflows July 14, 2025
  • [Argo Workflow] SSO Authentication for Argo Workflows. July 14, 2025
  • [AWS/EKS] Cache Docker image to accelerate EKS container deployment. July 10, 2025
  • [Laravel] Laravel Helpful June 26, 2025

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.