Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 6 - Exception Handling

6.3 Raising Exception

Raising exceptions in Python allows you to handle errors gracefully, particularly when dealing with potential invalid inputs from users or other sources.

Let's examine the example provided:

def greet(name):
    if not isinstance(name, str):
        raise TypeError("Name must be a string")
    print("Hello,", name)

greet(123)

In the greet() function:

  • The function expects name to be a string.
  • It uses isinstance(name, str) to check if name is indeed a string. If name is not a string (str), it raises a TypeError with the message "Name must be a string".
  • If name is a valid string, it proceeds to greet the person with "Hello, {name}".

When you call greet(123), where 123 is an integer instead of a string, Python will raise a TypeError because integers are not instances of str. This demonstrates the importance of validating input types to ensure your program behaves as expected.

Now, try passing your name (as a string) to the greet() function:

In this case, the function will execute without errors and print "Hello, Alice" as expected, because "Alice" is a valid string input.

By using the raise statement with specific exceptions like TypeError, you can provide clear error messages and handle invalid input scenarios effectively in your programs.