Raising Exceptions

Python · Exception Handling

Theory

raise lets your own code signal an error. raise ValueError('Salary cannot be negative') creates an exception object with a message and throws it; the current function stops at once and Python looks for a matching except up the call stack. If nothing catches it, the program stops and prints the message in the traceback.

Choose a built-in type that describes the problem: ValueError for a bad value, TypeError for a wrong type, KeyError for a missing key. For business-specific errors you can define your own class, class InsufficientBalanceError(Exception): pass, and raise it. Inside an except block, a bare raise re-raises the current exception after you log it, and raise NewError(...) from e wraps it while keeping the original cause in the traceback.

Why we use it

Failing fast with a clear message is better than letting bad data flow on silently. raise lets functions enforce their rules - no negative salary, no empty file - and tell the caller exactly what went wrong.

When to use it

Raise when a function gets input it cannot handle or a business rule is broken. Do not raise for normal, expected outcomes (like 'no rows found'); returning an empty result is usually better there.

How it works

  1. Call set_salary(-100)
  2. Is value < 0? Yes: raise ValueError('Salary cannot be negative'). No: Return the value normally.
  3. Function stops; Python searches for a handler
  4. Does a caller catch ValueError? Yes: Handle it, e.g. print(e). No: Program stops with a traceback.
  5. Clear error message shown

Syntax

raise ExceptionType("message")

Example

def set_salary(value):
    if value < 0:
        raise ValueError("Salary cannot be negative")
    return value

try:
    set_salary(-100)
except ValueError as e:
    print(e)

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic