Skip to content

Instantly share code, notes, and snippets.

@SamuelM333
Last active November 2, 2018 14:30
Show Gist options
  • Save SamuelM333/2655e6af2157a37ccbeef4826a568c35 to your computer and use it in GitHub Desktop.
Save SamuelM333/2655e6af2157a37ccbeef4826a568c35 to your computer and use it in GitHub Desktop.

Manejo de Excepciones

Que es una excepción?

Anomalous or exceptional conditions requiring special processing.

Que es una excepción?

Ejemplos de excepciones

  • ZeroDivisionError
  • IntegrityError
  • KeyError
  • NullPointerException

Cómo detectar excepciones

  • Pensar en los casos de excepción más probables
  • Probando!
  • En producción…

Produccion

Qué hacer cuando encontramos excepciones

Casos favorables y de excepción

def inverso(x):
    try:
        inverso = 1/x
        return inverso
    except ZeroDivisionError:
        print("X no puede ser 0")
        return None

“Easier to ask for forgiveness than permission”

try:
    os.mkdir("carpeta_que_ya_existe")
except FileExistsError:
    pass

Manejar diferentes excepciones al mismo tiempo

En bloques diferentes

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

En el mismo bloque

try:
    x = int(input("Introduzca un numero: "))
    inverso = 1/x
    print(inverso)
except (ZeroDivisionError, ValueError):
    print("Debe introducir un numero diferente a cero")

Anidadas

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

Finally y Else

try:
    # block-1 ...
except Exception1:
    # handler-1 ...
except Exception2:
    # handler-2 ...
else:
    # else-block
finally:
    # final-block

Logging

Definición

Logging is the process of keeping a record of all data input, processes, data output, and final results in a program.

Niveles de logging

Niveles de logging

Logging Formatters

logging.Formatter('%(process)d: %(asctime)s - %(levelname)s - %(message)s')

Logging Formatters

Logging Handlers

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

Crear nuestras propias excepciones

Como y cuando

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

Rol de las excepciones

Las excepciones solo deben describir el error que se ocasionó, no intentar resolverlo.

Fuentes y further reading

https://en.wikipedia.org/wiki/Exception_handling

https://docs.quantifiedcode.com/python-anti-patterns/readability/asking_for_permission_instead_of_forgiveness_when_working_with_files.html

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

https://docs.python.org/3/library/logging.handlers.html

https://julien.danjou.info/python-exceptions-guide/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment