π Master Python Like a Pro: Exception Handling, raise, Lambda Functions & Recursion Explained

Whether you're building small scripts or large-scale applications, mastering Pythonβs exception handling and functional programming concepts like lambda functions and recursion can significantly level up your code quality and maintainability.
In this article, weβll cover:
π§ Try, Except, Else, and Finally Blocks in Python
π¨ Raising and Handling Multiple Exceptions
π§ Lambda Functions & Recursion Explained with Real Examples
β Mastering Exception Handling in Python: Try, Except, Else, and Finally Explained
Exception handling allows your code to gracefully handle errors and maintain stability without crashing unexpectedly.
πΉ try-except
Block
Python wraps risky code inside a try
block and handles exceptions in the except
block.
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
πΉ else
Block
Runs only if no exception occurs.
try:
num = int(input("Enter a number: "))
except ValueError:
print("That's not a number.")
else:
print(f"You entered: {num}")
πΉ finally
Block
Always runs, regardless of exceptions. Perfect for cleanup tasks like closing files or releasing resources.
try:
f = open("data.txt", "r")
content = f.read()
except FileNotFoundError:
print("File not found.")
finally:
f.close()
print("File closed.")
π§ Best Practice: Always use finally
when working with I/O or database connections.
π¨ Using the raise
Keyword and Managing Multiple Exceptions in Python
πΉ Using raise
to Trigger Custom Errors
You can throw exceptions manually using the raise
keyword.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
π Why use raise
?
For enforcing constraints
For debugging with meaningful error messages
πΉ Handling Multiple Exceptions
You can handle different types of exceptions separately.
try:
value = int(input("Enter a number: "))
result = 100 / value
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
π Using a Tuple for Multiple Exceptions
try:
risky_operation()
except (TypeError, IndexError) as e:
print(f"Error occurred: {e}")
π§ Introduction to Lambda Functions and Recursion in Python Programming
β‘ Lambda Functions: Anonymous One-Liners
Lambda functions are small, anonymous functions often used with map()
, filter()
, and sorted()
.
π Syntax:
lambda arguments: expression
π Example 1: Square of a Number
square = lambda x: x * x
print(square(4)) # Output: 16
π Example 2: Sorting with Custom Key
names = ["jugal", "kishore", "ai", "python"]
sorted_names = sorted(names, key=lambda name: len(name))
print(sorted_names)
π§ Use Case: Quick one-time use functions without defining def
blocks.
π Recursion: Function Calling Itself
Recursion is a method where a function calls itself to solve a smaller version of the problem.
π Example: Factorial Using Recursion
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
β οΈ Watch Out For:
Base case to prevent infinite recursion
RecursionError
if the depth is too high
π§ When to Use What?
Feature | Use Case Example |
try-except | Wrapping code that might raise an error |
else | Run code only if try block is successful |
finally | Always run for cleanup (e.g., closing files) |
raise | Throw custom errors (e.g., input validation) |
Lambda | Small, anonymous functions used briefly |
Recursion | Problems naturally defined recursively (e.g., trees) |
π Conclusion
From handling errors like a pro to writing elegant one-liners with lambdas and solving problems recursively, these Python features can make your code more robust, efficient, and clean.
β
Learn them.
π§ͺ Practice them.
π Use them in your projects!
Subscribe to my newsletter
Read articles from Jugal kishore directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
