-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexception_handling.py
More file actions
41 lines (36 loc) · 932 Bytes
/
exception_handling.py
File metadata and controls
41 lines (36 loc) · 932 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Try
try:
# Code that might throw and exception
resultado = 10 / 0 # Division by cero
print (resultado)
except ZeroDivisionError:
print("Error: División por cero")
# Except
try:
# Code that might throw and exception
resultado = 10 / 0 # Division by cero
print (resultado)
except ZeroDivisionError:
print("Error: División por cero")
except ValueError:
print("Error: Valor inválido")
# Finally
try:
# Code that might throw and exception
archivo = open("archivo.txt", "r")
# Make operations with the file
print("Archivo encontrado")
except FileNotFoundError:
print("Error: Archivo no encontrado")
finally:
archivo.close() # Close the file forever, even if it throws and exception
# Custom exception
registrado = False
def funcion():
# Code that might throw an exception
if not registrado:
raise Exception("No se ha registrado")
try:
funcion()
except Exception as e:
print(f"Error: {str(e)}")