本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペースはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらく

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシープライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
012345678901234567890123456789012345678901234567890123456789
昨日
012345678901234567890123456789012345678901234567890123456789
累計閲覧
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

Python ドキュメント
Python
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
ディスカッション

Python ガイド · 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 . The original cause stays attached to the traceback, which makes debugging much easier.

この章について質問がありますか?
前の章Modules and Packages次の章Key Concepts
raise NewError(...) from e

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.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。