% Excepciones
%
%

# Motivación

----


```python
1 / 0

ZeroDivisionError: division by zero
```


```python
datos = [1, 2, 3]
datos[5]

IndexError: list index out of range
```


```python
a = 1
b = "2"
a + b

TypeError: unsupported operand type(s) for +: 'int' and 'str'
```

. . .

Cuando aparece el error, el programa se detiene

. . .

Puedo **evitar** errores usando `if`s

----

:::::::::::::::::::::::::::::::: {.columns}

:::{.column width="50%"}

```
import requests

pagina_horario = requests.get(
    "http://artemisa.unbosque.edu.co"
)
```

:::
:::{.column width="50%"}

![](ex-requests.png){ width="700px" }

:::
::::::::::::::::::::::::::::::::

-----

:::::::::::::::::::::::::::::::: {.columns}

:::{.column width="50%"}

![](ex-1.png){ width="100%" }

:::
:::{.column width="50%"}

![](ex-2.png){ width="100%" }

:::
::::::::::::::::::::::::::::::::

. . .

La página está caída / no hay internet / escribí mal la dirección

. . .

**No puedo** evitar los errores con `if`s

## Manejo de excepciones

:::::::::::::::::::::::::::::::: {.columns}

:::{.column width="50%"}


```python
def f1(a, b):
    print(a / b)

    print('fin de función')

f1(1, 0)
```

:::

:::{.column width="50%"}
```python
def f2(a, b):
    try:
        print(a / b)
    except:
        print('No se puede hacer la división')

    print('fin de función')

f2(1, 0)
```
::: 

::::::::::::::::::::::::::::::::

-----

¿y si no quiero hacer nada cuando ocurre un error?

. . .

```python
def f2(a, b):
    try:
        print(a / b)
    except:
        pass

    print('fin de función')

f2(1, 0)
```
------

```python
def f3(a, b):
    try:
        print(a / b)
    except TypeError:
        print('alguno de los datos no es entero')
    except ZeroDivisionError:
        print('b es cero, no puedo dividir')

    print('fin de función')

f3(1, 0)
f3(1, "2")
```
