Raising Exceptions

In Python, you can manually trigger (raise) an error using the raise keyword.

This is useful when you want to:

  • Stop program execution
  • Enforce rules or validations
  • Create custom error messages
  • Prevent invalid data

BASIC SYNTAX

raise ExceptionType("Error message")

SIMPLE EXAMPLE

age = -5if age < 0:
raise ValueError("Age cannot be negative.")

If the condition is true, Python will stop execution and show the error.

RAISING EXCEPTION WITH USER INPUT

num = int(input("Enter a positive number: "))if num <= 0:
raise ValueError("Number must be positive.")print("You entered:", num)

This ensures only valid input is accepted.

RAISING DIFFERENT TYPES OF EXCEPTIONS

name = ""if not name:
raise TypeError("Name cannot be empty.")

You can raise:

  • ValueError
  • TypeError
  • ZeroDivisionError
  • FileNotFoundError
  • Or other built-in exceptions

RAISE WITH TRY-EXCEPT

try:
num = int(input("Enter number: "))
if num == 0:
raise ZeroDivisionError("Zero is not allowed.")
except ZeroDivisionError as e:
print("Error:", e)

Here, we manually raised an exception and handled it.

CREATING CUSTOM EXCEPTIONS

You can create your own exception class.

class InvalidAgeError(Exception):
passage = -1if age < 0:
raise InvalidAgeError("Invalid age entered.")

Custom exceptions make programs more professional and organized.

WHY USE RAISE?

• Validate user input
• Enforce business rules
• Stop incorrect program flow
• Improve debugging
• Build secure applications

KEY POINTS

• Use raise to trigger an exception manually
• Provide clear error messages
• Can be used with built-in or custom exceptions
• Works together with try and except

Raising exceptions helps you control errors instead of waiting for them to happen automatically.

Home » PYTHON INTERMEDIATE (PYI) > Exception Handling > Raising Exceptions