# Roots with Exception Handling¶

In [2]:
import math

In [7]:
math.sqrt(-1)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-2037b8d41d70> in <module>()
----> 1 math.sqrt(-1)

ValueError: math domain error
In [32]:
def roots4():
try:
a, b, c = eval(input("Please enter three coefficients (a,b,c): "))
disc_root = math.sqrt(b**2 - 4 * a * c)
root1 = (-b + disc_root)/(2*a)
root2 = (-b - disc_root)/(2*a)
print("The solutions are: {0} {1}".format(root1, root2))
except ValueError as exc:
print(type(exc))
desc = str(exc)
if desc == "too many values to unpack (expected 3)":
print("You entered too many coefficients!")
elif desc in ["not enough values to unpack (expected 3, got 2)",
"not enough values to unpack (expected 3, got 1)"]:
print("You entered too few coefficients!")
elif desc == "math domain error":
print("No real roots!")
else:
print("Unexepected exception: {0}".formt(desc))
except NameError:
except TypeError as exc:
if str(exc) == "'int' object is not iterable":
print("You entered too few coefficients!")

In [8]:
roots4()

Please enter three coefficients (a,b,c): 1,2,3
No real roots!

In [13]:
roots4()

Please enter three coefficients (a,b,c): foo

In [22]:
roots4()

Please enter three coefficients (a,b,c): 1,2,3,4
You entered too many coefficients!

In [23]:
roots4()

Please enter three coefficients (a,b,c): 1,2
You entered too few coefficients!

In [25]:
roots4()

Please enter three coefficients (a,b,c): 1,
You entered too few coefficients!

In [28]:
roots4()

Please enter three coefficients (a,b,c): 1
You entered too few coefficients

In [34]:
roots4()

Please enter three coefficients (a,b,c): 1,2,3,4
<class 'ValueError'>
You entered too many coefficients!

In [36]:
help(math.sqrt)

Help on built-in function sqrt in module math:

sqrt(...)
sqrt(x)

Return the square root of x.


In [47]:
def roots5():
try:
a, b, c = eval(input("Please enter three coefficients (a,b,c): "))
disc_root = math.sqrt(b**2 - 4 * a * c)
root1 = (-b + disc_root)/(2*a)
root2 = (-b - disc_root)/(2*a)
print("The solutions are: {0} {1}".format(root1, root2))
except Exception as exc:  # A "bare" except
print("An exception occurred: {0}".format(str(exc)))

In [48]:
roots5()

Please enter three coefficients (a,b,c): 1,2,3,4
An exception occurred: too many values to unpack (expected 3)

In [50]:
try:
print("Hello World")
finally:
print("Goodbye World")

  File "<ipython-input-50-7dbaa38967be>", line 3
else:
^
SyntaxError: invalid syntax