Learn Python
Lesson 1 - Introduction To Python
Lesson 2 - Basic Python Syntax
Lesson 3 - Control Flow
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
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:
name
to be a string.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"
.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.