Python Docs

Python "raise" — Raise Exception Cheat Sheet

What is "raise" in Python?

The raise keyword allows developers to manually trigger an exception. It is used when your program must stop or warn the user when something is invalid.

Why Use raise?

  • Validate input values
  • Stop program execution when something is wrong
  • Create custom controlled error messages
  • Ensure code correctness by enforcing conditions

Basic Example: Raise a General Exception

Stops the program if the condition is invalid:

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")

If x is less than 0, Python immediately raises an Exception with a custom message.

Raise Specific Exception Types

You don't have to raise a generic Exception. You can raise specific built-in exceptions like TypeError, ValueError, ZeroDivisionError, etc.

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")

Here, a TypeError is raised when the value is not an integer.

Common Exceptions You Can Raise

Exception TypeWhen to Use
ExceptionGeneric error for general conditions
ValueErrorValue is invalid
TypeErrorWrong data type
KeyErrorMissing dictionary key
IndexErrorIndex out of range
ZeroDivisionErrorDivision by zero attempted

Summary

  • raise manually triggers exceptions
  • Great for input validation and enforcing rules
  • Use built-in exceptions (TypeError, ValueError, etc.)
  • You can attach a custom message
  • Program execution stops immediately when raised