Advertisement
teslariu

manejo excepciones

Aug 23rd, 2023
1,099
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. Script que pide dos numeros y devuelve su cociente
  6.  
  7. def ingresar(n):
  8.     while True:
  9.         try:
  10.             numero = float(input(f"Ingrese el {n}º nro: "))
  11.         except ValueError:
  12.             print("Error, debe ingresar un número")
  13.         else:
  14.             return numero
  15.            
  16. def dividir(a,b):
  17.     if b:
  18.         return f"{a}/{b} = {a/b}"
  19.     else:
  20.         return "No se puede dividir por cero"
  21.  
  22.  
  23.        
  24. a = ingresar(1)
  25. b = ingresar(2)
  26. print(dividir(a,b))
  27.  
  28. Pseudocódigo
  29. 1)
  30.  
  31. try:
  32.     descargar una pagina web
  33. except NoExisteLaPaginaError:
  34.     print("No existe la página")
  35.  
  36. except ConexionRechazadaError:
  37.     print("Conexiòn rechazada")
  38.    
  39. except ServidorNoRespondeError:
  40.     print("Servidor no responde")
  41.  
  42.  
  43. 2)
  44. try:
  45.     algo
  46. except (error1, error2, error3):
  47.     print("Error 1, 2 o 3")
  48.  
  49.  
  50. 3)
  51. try:
  52.     algo
  53.     otra cosa   # conviene una UNICA instruccion dentro de try
  54. except Exception:
  55.     print("Error")  # captura cualquier error
  56. """
  57. # manejo de excepciones dentro de una función
  58.  
  59. def sumar(a,b):
  60.     """
  61.     Función que recibe dos números como argumentos y devuelve
  62.     su suma. Lanza una excepción si los argumentos no son numéricos  
  63.     """
  64.     if not isinstance(a,(int,float)) or not isinstance(b,(int,float)):
  65.         raise TypeError("Los argumentos deben ser numéricos")
  66.    
  67.     return a + b
  68.  
  69. print(sumar(25,25.3))
  70. print(sumar("HO","LA"))
  71. print(sumar([2,3],[7,8]))
  72.  
  73.  
  74.  
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement