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

Jugal kishoreJugal kishore
3 min read

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:

  1. πŸ”§ Try, Except, Else, and Finally Blocks in Python

  2. 🚨 Raising and Handling Multiple Exceptions

  3. 🧠 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?

FeatureUse Case Example
try-exceptWrapping code that might raise an error
elseRun code only if try block is successful
finallyAlways run for cleanup (e.g., closing files)
raiseThrow custom errors (e.g., input validation)
LambdaSmall, anonymous functions used briefly
RecursionProblems 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!

0
Subscribe to my newsletter

Read articles from Jugal kishore directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jugal kishore
Jugal kishore