Anomalous or exceptional conditions requiring special processing.
ZeroDivisionError
IntegrityError
KeyError
NullPointerException
- Pensar en los casos de excepción más probables
- Probando!
- En producción…
def inverso(x):
try:
inverso = 1/x
return inverso
except ZeroDivisionError:
print("X no puede ser 0")
return None
try:
os.mkdir("carpeta_que_ya_existe")
except FileExistsError:
pass
try:
x = int(input("Introduzca un numero: "))
inverso = 1/x
print(inverso)
except ValueError:
print("Debe introducir un numero")
except ZeroDivisionError:
print("Debe introducir un numero diferente a cero")
try:
x = int(input("Introduzca un numero: "))
inverso = 1/x
print(inverso)
except (ZeroDivisionError, ValueError):
print("Debe introducir un numero diferente a cero")
try:
x = int(input("Introduzca un numero: "))
try:
inverso = 1/x
print(inverso)
except ZeroDivisionError:
print("Debe introducir un numero diferente a cero")
except ValueError:
print("Debe introducir un numero")
try:
# block-1 ...
except Exception1:
# handler-1 ...
except Exception2:
# handler-2 ...
else:
# else-block
finally:
# final-block
Logging is the process of keeping a record of all data input, processes, data output, and final results in a program.
logging.Formatter('%(process)d: %(asctime)s - %(levelname)s - %(message)s')
import logging.handlers
import sys
LOGFILE = 'proceso.log'
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(process)d: %(asctime)s - %(levelname)s - %(message)s')
stdout_logger = logging.StreamHandler(sys.stdout)
stdout_logger.setLevel(logging.INFO)
stdout_logger.setFormatter(formatter)
logger.addHandler(stdout_logger)
file_handler = logging.FileHandler(LOGFILE)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
rotating_file_handler = logging.handlers.TimedRotatingFileHandler(LOGFILE, when="W6")
rotating_file_handler.setFormatter(formatter)
rotating_file_handler.setLevel(logging.INFO)
logger.addHandler(rotating_file_handler)
logging.info()
logging.warning()
logging.error()
logging.critical()
logging.exception()
raise Exception("Mensaje de error")
class CustomException(Exception):
"""Mensaje de error"""
class CarError(Exception):
"""Basic exception for errors raised by cars"""
def __init__(self, car, msg=None):
if msg is None:
# Set some default useful error message
msg = "An error occured with car %s" % car
super(CarError, self).__init__(msg)
self.car = car
class CarCrashError(CarError):
"""When you drive too fast"""
def __init__(self, car, other_car, speed):
super(CarCrashError, self).__init__(
car, msg="Car crashed into %s at speed %d" % (other_car, speed))
self.speed = speed
self.other_car = other_car
try:
drive_car(car) # Esta funcion llama a raise CarCrashError
except CarCrashError as e:
# If we crash at high speed, we call emergency
if e.speed >= 30:
call_911()
Las excepciones solo deben describir el error que se ocasionó, no intentar resolverlo.
https://en.wikipedia.org/wiki/Exception_handling
https://wiki.python.org/moin/HandlingExceptions
https://stackify.com/specify-handle-exceptions-java/
https://docs.python.org/3.6/library/logging.html
https://www.loggly.com/ultimate-guide/java-logging-basics/
https://realpython.com/python-exceptions/
https://docs.python.org/2.5/whatsnew/pep-341.html
https://www.quora.com/What-is-Logging-in-programming
https://docs.python.org/3/howto/logging.html