Python Learning Series · @onlysamarrr · Day 25 / 30

Day 25: finally, raise, Custom Errors

Day 25 covers else and finally, plus raise and custom exceptions. You raise your own error with raise, and you create a custom exception class by inheriting from Exception.

Phase: Intermediate · Reels: 121/450 – 125/450

Quick Answer

Day 25 covers else and finally, plus raise and custom exceptions. You raise your own error with raise, and you create a custom exception class by inheriting from Exception.

What You Will Learn

Code

class AgeError(Exception):
    pass

def set_age(age):
    if age < 0:
        raise AgeError("Age cannot be negative")
    return age

try:
    set_age(-5)
except AgeError as e:
    print(e)
print(set_age(21))

Output

Age cannot be negative
21

Code Explained, Line by Line

  1. class AgeError(Exception) creates a custom exception by inheriting from Exception.
  2. raise AgeError(...) throws the error yourself when the age is negative.
  3. except AgeError as e catches only this error, not other errors.
  4. To keep the original error, write raise X from e.
  5. A custom exception's name itself explains what went wrong, which makes debugging easier.
Common Mistake: Hiding an error with except: pass is wrong: it makes debugging much harder because the failure disappears silently.

Real-Life Use

Age checks, payment validation and booking rules use custom exceptions in real apps.

Practice Task: Build an age validator: raise your own error for a negative age, return the age when it is valid.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. How do you create a custom exception?

Q2. What does raise do?

Q3. Why is except: pass bad?

Today's 5 Reels (from the 90-Day Plan Excel)

121/450Conceptelse aur finally
122/450Live demoraise se apna error
123/450Common mistakeError chhupana galat
124/450QuizQuiz: age validator
125/450Interview / real lifeInterview: custom exception
← Day 24Day 26 →