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()