How do I manually throw/raise an exception in Python?

To manually throw/raise an exception in Python, use the raise keyword. You can raise built-in exceptions or custom exceptions. Here’s how:

1. Basic Syntax

raise ExceptionType("Optional error message")

2. Raise a Built-in Exception

Example: Raise a ValueError when invalid input is detected.

def calculate_square_root(x):
    if x < 0:
        raise ValueError("Input must be non-negative")
    return x ** 0.5

try:
    calculate_square_root(-5)
except ValueError as e:
    print(f"Error: {e}")  # Output: Error: Input must be non-negative

3. Raise a Custom Exception

Create a custom exception class (inherits from Exception):

class InvalidEmailError(Exception):
    """Raised when an email format is invalid"""
    pass

def validate_email(email):
    if "@" not in email:
        raise InvalidEmailError(f"Invalid email: {email}")

try:
    validate_email("user.example.com")
except InvalidEmailError as e:
    print(e)  # Output: Invalid email: user.example.com

4. Re-raise an Exception

Capture an exception and re-raise it (e.g., for logging):

try:
    # Code that might fail
    x = 1 / 0
except ZeroDivisionError:
    print("Logging the error...")
    raise  # Re-raise the same exception

5. Raise Without Specifying an Exception

Not recommended, but possible (raises a generic RuntimeError):

if error_condition:
    raise  # ❌ Avoid: Only works inside an except block

Common Built-in Exceptions

Exception TypeUse CaseExample
ValueErrorInvalid value for a functionraise ValueError("Invalid input")
TypeErrorIncorrect type passed to a functionraise TypeError("Expected str")
FileNotFoundErrorFile/directory not foundraise FileNotFoundError("Missing file")
KeyErrorMissing dictionary keyraise KeyError("Key not found")
RuntimeErrorGeneric error for unexpected conditionsraise RuntimeError("Unexpected state")

Best Practices

  1. Use specific exceptions (e.g., ValueError instead of generic Exception).
  2. Include meaningful messages to clarify the error.
  3. Create custom exceptions for domain-specific errors.

By raising exceptions, you can enforce constraints and improve error handling in your code.

Leave a Reply

Your email address will not be published. Required fields are marked *