Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack safer

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
012345678901234567890123456789012345678901234567890123456789
Yesterday
012345678901234567890123456789012345678901234567890123456789
Total views
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Python docs
Python
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
Discussions

Python guide · 5/6

Errors and Testing

Python reports problems by raising exceptions rather than returning error codes. This chapter covers the four parts of a try statement, raising your own exceptions and designing exception hierarchies, context managers for reliable cleanup, and testing your code with pytest and the standard unittest module.

Exceptions and the try statement

When an exception is raised, normal execution stops and Python unwinds the call stack looking for a matching handler. If none is found, the program prints a traceback and exits. A try statement has up to four clauses:

ClauseRuns when
tryAlways; this is the code that might fail
exceptAn exception of the listed type was raised
elseThe try block finished without raising
finallyAlways, last, whether or not something failed
def read_number(path: str) -> int:
    try:
        f = open(path, encoding="utf-8")
    except FileNotFoundError:
        print(f"{path} does not exist")
        return 0
    else:
        try:
            return int(f.read().strip())
        except ValueError as e:
            print(f"not a number: {e}")
            return 0
        finally:
            f.close()   # runs on success and on failure

Catch only the exceptions you can actually handle. A bare except: or a blanket except Exception: swallows genuine bugs along with the failure you expected. To handle several types the same way, list them in a tuple: except (KeyError, IndexError):.

Raising and defining exceptions

Use raise when input or state is invalid. For domain-specific failures, subclass Exception. A common pattern is one base class per library with more specific subclasses underneath, so callers can catch broadly or narrowly as they prefer.

class PaymentError(Exception):
    """Base class for payment failures."""


class InsufficientFunds(PaymentError):
    def __init__(self, needed: int, available: int) -> None:
        super().__init__(f"needed {needed}, only {available} available")
        self.needed = needed
        self.available = available


def pay(balance: int, amount: int) -> int:
    if amount <= 0:
        raise ValueError("amount must be positive")
    if amount > balance:
        raise InsufficientFunds(amount, balance)
    return balance - amount


try:
    pay(1000, 5000)
except PaymentError as e:
    print("payment failed:", e)

When you catch a low-level error and re-raise something more meaningful, write raise NewError(...) from e. The original cause stays attached to the traceback, which makes debugging much easier.

Context managers and with

Files, network connections and locks must be released after use. The with statement guarantees that cleanup happens when the block exits, even if an exception escapes it, and it reads far better than a hand-written try/finally. To write your own, the contextlib.contextmanager decorator turns a generator into a context manager.

import time
from contextlib import contextmanager

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
# the file is already closed here


@contextmanager
def timer(label: str):
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed:.3f}s")


with timer("summing"):
    total = sum(range(1_000_000))

Testing with pytest

pytest is the most popular testing tool in the Python world. It discovers files and functions whose names start with test_, and it lets you use the plain assert statement; when an assertion fails, it shows you exactly which values differed.

# tests/test_pay.py
import pytest

from payments import InsufficientFunds, pay


def test_pay_reduces_balance():
    assert pay(1000, 300) == 700


def test_pay_rejects_overdraft():
    with pytest.raises(InsufficientFunds):
        pay(100, 500)


@pytest.mark.parametrize("amount", [0, -10])
def test_pay_rejects_non_positive(amount):
    with pytest.raises(ValueError, match="positive"):
        pay(1000, amount)


def test_writes_file(tmp_path):
    target = tmp_path / "out.txt"   # a fresh temporary directory per test
    target.write_text("ok", encoding="utf-8")
    assert target.read_text(encoding="utf-8") == "ok"
python -m pip install pytest
pytest                   # run the whole suite
pytest -k overdraft -v   # only tests matching "overdraft", verbosely

Requesting tmp_path simply by naming it as a parameter is an example of a fixture: reusable setup that pytest injects for you. You can define your own with @pytest.fixture.

unittest

The standard library also ships unittest, so it works without installing anything. Tests are methods starting with test_ on a subclass of TestCase, and checks use methods such as assertEqual. pytest runs unittest-style tests too, so the two can coexist in one project.

import unittest

from payments import pay


class PayTest(unittest.TestCase):
    def test_pay(self):
        self.assertEqual(pay(1000, 300), 700)

    def test_negative(self):
        with self.assertRaises(ValueError):
            pay(1000, -1)


if __name__ == "__main__":
    unittest.main()

Summary

  • Handle failures with try/except/else/finally, catching only exceptions you can deal with.
  • Raise exceptions for invalid input, build a small hierarchy from Exception, and chain causes with from.
  • Manage anything that needs cleanup with with and context managers.
  • Write tests with pytest's assert, pytest.raises and fixtures; unittest remains available in the standard library.
Questions about this chapter?
Previous chapterModules and PackagesNext chapterKey Concepts

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.