"Swift 2.0 Collections and Control Flow" was retired on May 31, 2020. You are now viewing the recommended replacement.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Possible to raise two types of errors

Possible to raise two types of errors So I'm experimenting making my own program. I have the user input a string and an integer (name, age).

I want to raise a Value Error if the age is under 1 (if age > 1:) I did that. But I'm not sure what to do if the name is not a string. Is it a TypeError and can two types of errors be raised at the same time? If so how?

Probably got some terminology wrong but having trouble thinking right now.

Here's the code:

# This program asks name how old you are and makes exceptions to check and see if 
there are errors

def hogwarts_express (name, age):

    if age < 1:

        raise ValueError ("Error: Apparently you don't exist.  Please pick a number older 
than 0!")

    if int (age) >= 10:
        print ("Hello {}!  Welcome to the Hogwarts Express, your old enough to go now.  
Here 's your ticket!".format(name))
    else:
        print ("Sorry {} you're not old enough to board the express.".format(name))
try:
    your_name = input("What's your name?  ")
    age = int(input("How old might you be?  "))
    together = hogwarts_express (your_name, age)

except ValueError as err:
    print ("That's not a valid value.  Please input something else.")
    print ("{}".format(err))

else:
    print (together)

2 Answers

Hi Mikaela,

Yes, you can absolutely have two (or more) recognised exceptions for a single try.

However, in the specific case you describe, you actually only have one type of error: ValueError: The input() method will always return a string regardless of what the user types. You can prove this to yourself in the REPL:

user_input = input("type a number > ")

Then enter a number, e.g., 3. Next ask Python what the type is:

type(user_input)

Python will reply: <class 'str'>

You are right to think about TypeErrors, though. Suppose that instead of getting the name straight from input(), it was passed into a function:

def greet_student(name):
    print("hello " + name)

This function works exactly as intended if it is called with a string, but we get the TypeError you were concerned about if we accidentally call it with a number.

Now, what about mixing two error types? Suppose the greet_function function only liked people with names shorter than 8 characters,

def greet_student(name):
    if len(name) > 7:
        raise ValueError("name must be shorter than 8 characters, {} is {} chars.".format(name, len(name)))
    print("hello " + name)

Now, if we pass this function "mikaela", the function prints "hello mikaela". If we pass 'alexander', the function raises a ValueError and tells us that we have too many characters. If we pass a number, we get a TypeError.

In our calling code we can handle those different error types:

name = 'harry' # we can experiment with different values for name, e.g., 'dumbledore' or 17
try:
    greet_student(name)
except ValueError as err:
    print(err)
except TypeError as err:
    print(err)
else:
    print("Welcome to Hogwarts")

This code will print the greeting if the name is valid or print the appropriate exception text depending on the error. If there is no error, the else text will be printed as well.

Hope that clears everything up for you.

Cheers

Alex

Hi Mikaela Land,

In your example variable "your_name" will come as string and if you pass integer it will come as string too. So no errors will be raised. However if you want to handle the case of if someone try to provide integer instead of string then you can handle it as below:

>>> str2 = "123"                                                                                                                                 
>>> int(str2)                                                                                                                                    
123

Let's say str2 is a "your_name" variable, if you are able to convert it to "int" then raise an exception else allow them.

In your program there is no need to raise any other new exception. However, if you want to raise two exceptions it's possible. See the below code snippet:

a = "a"
b = 2

try:
    a - b
    age = int(a)
    age = 2
except TypeError:
    print("It's not possible")
except ValueError:
    print("Convert valid values")
else:
    print("This will never run") 

What exactly you need to do is:

  • try to find out which code could raise an exception.
  • add that code in try block and catch the exceptions in Except block.
  • you can re-raise an exception using raise keyword and reference them using 'as' keyword. Idea is Catch the exception and then raise that exception. I hope this will resolve the doubt.

Happy Coding