Exception Handling

In [1]:
import math
In [8]:
def roots4():    
    try:
        a,b,c = eval(input("Enter coeffecients (a, b, c):"))
        discrim = b**2 - 4 * a * c
        disc_root = math.sqrt(discrim)
        root1 = (-b + disc_root) / (2 * a)
        root2 = (-b - disc_root) / (2 * a)
        print("The solutions are: {0:0.3f} {1:0.3f}".format(root1, root2))
    except ValueError:
        print("No real roots!")
In [7]:
roots4()
Enter coeffecients (a, b, c):3,4,5
No real roots!
In [31]:
def roots5():    
    try:
        a,b,c = eval(input("Enter coeffecients (a, b, c):"))
        discrim = b**2 - 4 * a * c
        disc_root = math.sqrt(discrim)
        root1 = (-b + disc_root) / (2 * a)
        root2 = (-b - disc_root) / (2 * a)
        print("The solutions are: {0:0.3f} {1:0.3f}".format(root1, root2))
    except ValueError as exc:
        if str(exc) == "too many values to unpack (expected 3)":
            print("You've entered too many values!")
        elif str(exc) == "math domain error":
            print("No real roots!")
        else:
            print("Exception occurred: {0}".format(exc))
    except NameError:
        print("Bad input!")
    #except:
        # Bad idea, unless you know exactly what you are trying do.
    #    pass
    except Exception as exc:
        print("An unknown exception occurred: {0}".format(exc))
In [32]:
roots5()
Enter coeffecients (a, b, c):x = 10
An unknown exception occurred: invalid syntax (<string>, line 1)