Tecnicos PC

Página asociada a la lista Tecnicos PC.

sábado, agosto 18, 2007

Manejo de errores en Python

Forma "tradicional" de manejar errores:


if os.path.exists("noexistis.csv"):
fh=open("noexistis.csv")
linea=fh.readline()
fh.close()
if "\t" in linea:
valor=linea[:linea.index("\t")]
if valor.isdigit():
newvalue=int(valor)*.2
if os.access("/home/sbassi/out.txt",os.W_OK):
fw=open("out.txt","w")
fw.write(str(newvalue))
fw.close()
else:
print "Output file is not writable"
else:
print "It can't be converted to int"
else:
print "No tiene TAB"
else:
print "The file doesn't exist"

En Python podemos usar try/except para no tener que "deformar" el código en función de los posibles errores o situaciones no deseadas:

try:
fh=open("noexistis.csv")
linea=fh.readline()
fh.close()
valor=linea[:linea.index("\t")]
newvalue=int(valor)*.2
fw=open("/home/sbassi/out.txt","w")
fw.write(str(newvalue))
fw.close()
except IOError, (errno,errtext):
if errno==13:
print "Can't write to out.txt"
elif errno==2:
print "File not exist"
except ValueError, strerror:
if "substring not found" in strerror[0]:
print "There is no tab"
elif "invalid literal for int()" in strerror[0]:
print "It can't be converted to int"




Etiquetas: ,

Google Groups Suscribite a tecnicos-pc
Email:
Mirar archivos en groups.google.com