xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python try...catch All In One

Python try...catch All In One

Python 异常处理

try...except

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")
except (RuntimeError, TypeError, NameError):
  pass
class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

try...finally

try:
    raise KeyboardInterrupt
finally:
    print('Goodbye, world!')

demos

#!/usr/bin/env python3
# coding: utf8

import board
import neopixel
from time import sleep

PIN = board.D18
# 0.3W/LED (03mA ~ 60mA)
# LEDs = 60
LEDs = 30
# mode: GRB
ORDER = neopixel.GRB
pixels = neopixel.NeoPixel(PIN, LEDs, brightness=1.0, auto_write=True, pixel_order=ORDER)


# clear buffer ???
pixels.fill((0, 0, 0))
sleep(1)

try:
  while True:
    pixels[0] = (255, 0, 0)
    sleep(0.1)
    pixels[29] = (0, 255, 0)
    sleep(0.1)
except (ValueError, AttributeError, SyntaxError):
  print("value/attribute/syntax error ❌")
  # clear buffer
  pixels.deinit()

# try:
#   while True:
#     # hex
#     pixels[0] = (255, 0, 0)
#     # pixels[0] = (0x100000, 0, 0)
#     # pixels[0] = (0, 0xffffff, 0)
#     sleep(0.1)
#     pixels[29] = (0, 255, 0)
#     # pixels[29] = (0, 0xffffff, 0)
#     # pixels[29] = (0, 0x100000, 0)
#     sleep(0.1)
#   # except ValueError:
#   #   print("value error ❌")
#   # except AttributeError:
#   #   print("attribute error ❌")
#   # except SyntaxError:
#   #   print("syntax error ❌")
# except (ValueError, AttributeError, SyntaxError):
#   print("value/attribute/syntax error ❌")



"""
while True:
  for x in range(0, LEDs):
    # GRB => Green
    pixels.fill((255,0, 0))
    pixels.show()
    sleep(0.5)
    # GRB => Red
    pixels[x] = (0, 255, 0)
    sleep(0.1)

"""

"""
https://docs.circuitpython.org/projects/neopixel/en/latest/api.html#neopixel.RGB

https://docs.circuitpython.org/projects/neopixel/en/latest/_modules/neopixel.html#NeoPixel.deinit

https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel

# ✅
$ sudo ./neo-strip.py
"""

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print "Error: 没有找到文件或读取文件失败"
else:
    print "内容写入文件成功"
    fh.close()

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://docs.python.org/zh-cn/3/tutorial/errors.html

https://www.runoob.com/python/python-exceptions.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-05-11 22:27  xgqfrms  阅读(14)  评论(0编辑  收藏  举报