python raise ... from statement

aliases
No value
tags
No value
description
No value
links
http://legacy.python.org/dev/peps/pep-3134/ 0014 Python ๐Ÿ
status
No value
title
python raise ... from statement
created
2025-01-07T14:25:07
updated
2025-01-07T14:32:06

TL;DR

The "raise from" statement in Python is used to raise a new exception while preserving the context of the original exception. This allows you to provide additional information about the error that occurred, making debugging easier.

try:
    raise ValueError
except Exception as e:
    raise IndexError from e

PEP-3134

http://legacy.python.org/dev/peps/pep-3134/

๋‹ค์Œ ์ œ์•ˆ์—์„œ๋Š” ์„ธ๊ฐ€์ง€ dunder attributes๋“ค์ด ํฌํ•จ๋œ๋‹ค:

์ด ์ œ์•ˆ ๋•๋ถ„์— Python 3.0 ์ดํ›„๋ถ€ํ„ฐ ํ•˜๋‚˜์˜ ์˜ˆ์™ธ๊ฐ€ ๋‹ค๋ฅธ ์˜ˆ์™ธ์˜ ์˜ํ•ด ๋ฐœ์ƒํ–ˆ์Œ์„ ๋ช…์‹œ์ ์œผ๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๊ฒŒ๋œ๋‹ค.

์˜ˆ์ œ 1: raise ... from ...์œผ๋กœ ๋ช…์‹œ์  ์˜ˆ์™ธ ์ฒด์ธ ์„ค์ • (__cause__)

try:
    # ์ฒซ ๋ฒˆ์งธ ์˜ˆ์™ธ ๋ฐœ์ƒ
    raise ValueError("์›๋ž˜ ์˜ˆ์™ธ")
except ValueError as e:
    # ๋‘ ๋ฒˆ์งธ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋ฉฐ ์›๋ž˜ ์˜ˆ์™ธ๋ฅผ ๋ช…์‹œ์ ์œผ๋กœ ์—ฐ๊ฒฐ
    raise RuntimeError("์ƒˆ๋กœ์šด ์˜ˆ์™ธ") from e

์ถœ๋ ฅ ๊ฒฐ๊ณผ:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ValueError: ์›๋ž˜ ์˜ˆ์™ธ

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
RuntimeError: ์ƒˆ๋กœ์šด ์˜ˆ์™ธ

์˜ˆ์ œ 2: ์•”๋ฌต์  ์—ฐ๊ฒฐ (__context__)

try:
    # ์ฒซ ๋ฒˆ์งธ ์˜ˆ์™ธ ๋ฐœ์ƒ
    raise KeyError("์ฒซ ๋ฒˆ์งธ ์˜ˆ์™ธ")
except KeyError:
    # ๋‘ ๋ฒˆ์งธ ์˜ˆ์™ธ ๋ฐœ์ƒ (์•”๋ฌต์ ์œผ๋กœ ์—ฐ๊ฒฐ๋จ)
    raise TypeError("๋‘ ๋ฒˆ์งธ ์˜ˆ์™ธ")

์ถœ๋ ฅ ๊ฒฐ๊ณผ:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyError: '์ฒซ ๋ฒˆ์งธ ์˜ˆ์™ธ'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
TypeError: ๋‘ ๋ฒˆ์งธ ์˜ˆ์™ธ

์˜ˆ์ œ 3: __suppress_context__ = True๋กœ ์ด์ „ ์˜ˆ์™ธ ์–ต์ œ

try:
    # ์ฒซ ๋ฒˆ์งธ ์˜ˆ์™ธ ๋ฐœ์ƒ
    raise IndexError("์ฒซ ๋ฒˆ์งธ ์˜ˆ์™ธ")
except IndexError:
    # ์ด์ „ ์˜ˆ์™ธ๋ฅผ ์–ต์ œํ•˜๊ณ  ์ƒˆ๋กœ์šด ์˜ˆ์™ธ ๋ฐœ์ƒ
    ex = ValueError("๋‘ ๋ฒˆ์งธ ์˜ˆ์™ธ")
    ex.__suppress_context__ = True
    raise ex

์ถœ๋ ฅ ๊ฒฐ๊ณผ:

Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
ValueError: ๋‘ ๋ฒˆ์งธ ์˜ˆ์™ธ

์š”์•ฝ

์ด ๊ธฐ๋Šฅ์€ ๋””๋ฒ„๊น… ์‹œ ๋ฌธ์ œ์˜ ์›์ธ์„ ๋” ๋ช…ํ™•ํžˆ ํŒŒ์•…ํ•˜๋Š” ๋ฐ ๋งค์šฐ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค! ๐Ÿ˜Š