Skip to content

Commit 3577edc

Browse files
author
Saeid Darvish
committed
adding l24
1 parent ec97327 commit 3577edc

2 files changed

Lines changed: 184 additions & 0 deletions

File tree

index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
lessons/l21
5050
lessons/l22
5151
lessons/l23
52+
lessons/l24
5253
log
5354
donate-report
5455
python-interactive

lessons/l24.rst

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
.. role:: emoji-size
2+
3+
.. meta::
4+
:description: کتاب آموزش زبان برنامه نویسی پایتون به فارسی، مدیریت خطا در پایتون، raise Exception در پایتون، Warning در پایتون، Assertion پایتون
5+
:keywords: آموزش, آموزش پایتون, آموزش برنامه نویسی, پایتون, کتابخانه, پایتون, Exception در پایتون
6+
7+
8+
درس ۲۴: مدیریت خطا در پایتون: Warning ،raise Exception و Assertion
9+
===================================================================================================
10+
11+
.. figure:: /_static/pages/24-python-raise-exception-warning-assertion.jpg
12+
:align: center
13+
:alt: مدیریت خطا در پایتون:Warning ،raise Exception و Assertion
14+
15+
Photo by `Sandy Manoa <https://unsplash.com/photos/DnuC3-ZNBPQ>`__
16+
17+
18+
19+
20+
21+
توجه داشته باشید، هم اکنون پشتیبانی نسخه 2x پایتون به پایان رسیده است. بنابراین به منظور جلوگیری از پیچیدگی‌های غیر ضروری، تمام مطالب این درس بر مبنای پایتون 3x ارائه می‌شود.
22+
23+
24+
25+
:emoji-size:`` سطح: متوسط
26+
27+
----
28+
29+
30+
.. contents:: سرفصل‌ها
31+
:depth: 2
32+
33+
----
34+
35+
36+
دستور ``raise``
37+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
38+
39+
از درس پیش با Exception آشنا شدیم و مشاهده کردیم در زمان اجرای برنامه پایتونی تمامی خطاها در قالب یک Exception اعلام می‌گردند. اما در برنامه‌نویسی زمان‌های بسیاری خواهد بود که برنامه‌نویس می‌بایست خود اقدام به بروز Exception نماید. یک ماژول در هنگام انجام کار مشخصی ممکن است با وضعیت‌های مختلفی روبرو گردد که می‌بایست این وضعیت‌ها را به ماژول سطح بالاتر خود اعلام کند تا در نهایت نتیجه و توضیح مناسب برای کاربر فراهم گردد. برای مثال در پیاده‌سازی API ماژولی که انجام خدمت را به عهده دارد، هنگامی که به خطا یا وضعیتی خاص برخورد می‌کند، می‌تواند این وضعیت را در قالب بروز یک Exception اعلام می‌کند و ماژولی که وظیفه تولید پاسخ یا Response را برعهده دارد، بر اساس نوع Exception رخ داده می‌تواند یک Response مناسب تولید نماید.
40+
41+
در زبان برنامه‌نویسی پایتون از دستور ``raise`` [`اسناد پایتون <https://docs.python.org/3/reference/simple_stmts.html#raise>`__] برای بروز یک Exception استفاده می‌گردد::
42+
43+
raise exception_object
44+
45+
به نمونه کد زیر توجه نمایید:
46+
47+
.. code-block:: python
48+
:linenos:
49+
50+
def self_sum_int(a):
51+
if not isinstance(a, int):
52+
raise TypeError()
53+
54+
return a + a
55+
56+
res = self_sum_int('C')
57+
print(res)
58+
59+
60+
::
61+
62+
Traceback (most recent call last):
63+
File "sample.py", line 7, in <module>
64+
res = self_sum_int('C')
65+
File "sample.py", line 3, in self_sum_int
66+
raise TypeError()
67+
TypeError
68+
69+
در نمونه کد بالا ما یک شی از کلاس ``TypeError`` ایجاد و آن را raise کردیم (سطر ۳). همانطور که مشاهده می‌کنید، شرح Exception در Traceback (سطر پایانی) با آن چیزی که در درس پیش شاهد آن بودیم، متفاوت است و همچنین علت بروز Exception نیز raise شدن آن اعلام شده است.
70+
71+
می‌توان در هنگام نمونه‌سازی از کلاس Exception مورد نظر، یک متن دلخواه (یک شی از نوع ``str``) به عنوان شرح Exception در زمان نمونه‌سازی به صورت آرگومان ارسال کنیم:
72+
73+
74+
.. code-block:: python
75+
:linenos:
76+
77+
def self_sum_int(a):
78+
if not isinstance(a, int):
79+
raise TypeError(f"The input must be 'int' type, {a!r} is {type(a)}")
80+
81+
return a + a
82+
83+
res = self_sum_int('C')
84+
print(res)
85+
86+
87+
::
88+
89+
Traceback (most recent call last):
90+
File "sample.py", line 7, in <module>
91+
res = self_sum_int('C')
92+
File "sample.py", line 3, in self_sum_int
93+
raise TypeError(f'The input must be of the integer type, {a} is {type(a)}')
94+
TypeError: The input must be 'int' type, 'C' is <class 'str'>
95+
96+
97+
طی درس پیش مشاهده کردیم، چنانچه در زمان handle کردن یک Exception، یک Exception دیگر رخ دهد؛ در نتیجه Traceback نهایی نیز شامل یک Traceback به ازای هر Exception خواهد بود. این امکان نیز توسط دستور ``raise`` برای برنامه‌نویس فراهم می‌باشد. می‌توان با استفاده از دستور ``from`` در کنار ``raise``، دو Exception - که از نظر منطقی به یکدیگر وابسته هستند - را به یکدیگر متصل و سپس raise کرد::
98+
99+
raise exception_object from other_exception_object
100+
101+
به نمونه کد ساده زیر و خروجی آن توجه نمایید:
102+
103+
.. code-block:: python
104+
:linenos:
105+
106+
def sum_int(a, b):
107+
try:
108+
return a + b
109+
except Exception as exception:
110+
raise RuntimeError("Something bad happened") from exception
111+
112+
res = sum_int(3, 'C')
113+
print(res)
114+
115+
::
116+
117+
Traceback (most recent call last):
118+
File "sample.py", line 3, in sum_int
119+
return a + b
120+
TypeError: unsupported operand type(s) for +: 'int' and 'str'
121+
122+
The above exception was the direct cause of the following exception:
123+
124+
Traceback (most recent call last):
125+
File "sample.py", line 7, in <module>
126+
res = sum_int(3, 'C')
127+
File "sample.py", line 5, in sum_int
128+
raise RuntimeError("Something bad happened") from exception
129+
RuntimeError: Something bad happened
130+
131+
به عنوان یک نمونه کاربرد، از این روش می‌توان برای ایجاد یک Wrapper برای چندین Exception بهره برد. در این حالت کد سطح بالاتر تنها نیاز است یک نوع Exception را handle نماید:
132+
133+
.. code-block:: python
134+
:linenos:
135+
136+
def sum_int(a, b):
137+
try:
138+
return a + b
139+
except TypeError as type_err:
140+
raise RuntimeError(f'Something bad happened \n => {str(type_err)}') from type_err
141+
142+
143+
144+
try:
145+
res = sum_int(3, 'C')
146+
print(res)
147+
148+
except RuntimeError as runtime_err:
149+
print(f'{runtime_err.__class__.__name__}: {str(runtime_err)}')
150+
151+
::
152+
153+
RuntimeError: Something bad happened
154+
=> unsupported operand type(s) for +: 'int' and 'str'
155+
156+
ایجاد Exception
157+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
158+
159+
160+
Context Manager و ``with``
161+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
162+
163+
164+
ماژول warnings
165+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
166+
167+
168+
169+
دستور ``assert``
170+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
171+
172+
173+
174+
|
175+
176+
----
177+
178+
:emoji-size:`😊` امیدوارم مفید بوده باشه
179+
180+
`لطفا دیدگاه و سوال‌های مرتبط با این درس خود را در کدرز مطرح نمایید. <https://www.coderz.ir/python-tutorial-raise-exception-warnings-assertion>`_
181+
182+
183+

0 commit comments

Comments
 (0)