Advertisement
teslariu

excepciones

Aug 31st, 2022
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. Ejemplos de excepciones:
  6. 1) Bloque completo:
  7. try:
  8.    ....  # intento hacer esto
  9. except .....:
  10.    ....  # ejecuto esta linea si try lanza el error de la linea 9
  11. else:          
  12.    ......  # ejecuto esto si no hay error
  13. finally:
  14.    ......  # esto se ejecuta siempre, haya o no error
  15.    
  16. 2) except acepta varias formas
  17. try:
  18.    .....
  19. except (ValueError, NameError...):
  20.    ......  # se ejecuta si alguno de los errores de la linea 19 sucede
  21.  
  22. 3) try:
  23.        .....
  24.   except ValueError:
  25.        print("ValueError")
  26.   except NameError:
  27.        print("NameError")
  28.        
  29. 4) Si quiero capturar cualquier excepcion:
  30.    try:
  31.        .....
  32.    except Exception:
  33.        print("Excepción")
  34.  
  35.    o asi:
  36.    try:
  37.        .....
  38.    except:
  39.        print("Excepción")
  40.  
  41.    
  42. """
  43.  
  44.  
  45.  
  46.  
  47. """
  48. # Script que pide un numero no nulo y responde si este es positivo, negativo
  49. # o cero
  50.  
  51.  
  52. def ingresar_entero():
  53.    while True:
  54.        try:
  55.            numero = int(input("Ingrese un nro: "))
  56.        except ValueError:
  57.            print("Debe ingresar un nro entero...")
  58.        else:
  59.            return numero
  60.  
  61.            
  62. numero = ingresar_entero()        
  63.  
  64.  
  65. if numero > 0:
  66.    print("Positivo")
  67.  
  68. elif numero < 0:
  69.    print("Negativo")
  70.    
  71. else:
  72.    print("Cero")
  73. """
  74. # como implementar excepciones con funciones (lanzar excepciones)
  75.  
  76. def sumar(a,b):
  77.     """Función que toma como argumentos dos nros a y b y devuelve su suma"""
  78.     if not isinstance(a,(int,float)) or not isinstance(b,(int,float)):
  79.         raise TypeError("Se requieren dos números")
  80.     return a + b
  81.  
  82. print(sumar(1,2))
  83.  
  84. a =2
  85. b = 3
  86.  
  87. print(sumar("a","b"))
  88.  
  89. print([1,2,3],["Ana"])
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement