Manejo de Errores y Excepciones
Última modificación: Mayo 14, 2022
[1]:
def sqrt(x):
try:
return x ** 0.5
except:
print("x must be a float or integer")
display(
sqrt(1.0),
sqrt(-1.0),
sqrt("1"),
)
x must be a positive float or integer
1.0
(6.123233995736766e-17+1j)
None
[2]:
def sqrt(x):
try:
return x ** 0.5
except TypeError:
print("x must be a float or integer")
display(
sqrt(1.0),
sqrt(-1.0),
sqrt("1"),
)
x must be a float or integer
1.0
(6.123233995736766e-17+1j)
None
[3]:
def sqrt(x):
if x < 0:
raise ValueError("x must be > 0")
try:
return x ** 0.5
except TypeError:
print("x must be a float or integer")
display(
sqrt(1.0),
sqrt(-1.0),
sqrt("1"),
)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-f04da2c6748c> in <module>
10 display(
11 sqrt(1.0),
---> 12 sqrt(-1.0),
13 sqrt("1")
14 )
<ipython-input-3-f04da2c6748c> in sqrt(x)
1 def sqrt(x):
2 if x < 0:
----> 3 raise ValueError("x must be > 0")
4 try:
5 return x ** 0.5
ValueError: x must be > 0