Skip to content

Commit e4046f8

Browse files
author
Saeid
committed
l24: create Exception
1 parent 3577edc commit e4046f8

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

lessons/l24.rst

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,85 @@
156156
ایجاد Exception
157157
~~~~~~~~~~~~~~~~~~~~~~~~~~~
158158

159+
در زبان برنامه‌نویسی پایتون با ایجاد یک کلاس و ارث‌بری از ``Exception`` یا یکی از subclassهای آن می‌توان یک Exception جدید ایجاد نمود:
160+
161+
.. code-block:: python
162+
:linenos:
163+
164+
class NegativeNumberError(Exception):
165+
"""Raised when the input value is negative number"""
166+
pass
167+
168+
169+
def plus(num):
170+
if num < 0:
171+
raise NegativeNumberError(f'{num} is a negative number!')
172+
173+
return num + num
174+
175+
176+
try:
177+
print(plus(10))
178+
print('*' * 30)
179+
print(plus(-5))
180+
181+
except NegativeNumberError as err:
182+
print(str(err))
183+
184+
except:
185+
print('Something bad happened!')
186+
187+
::
188+
189+
20
190+
******************************
191+
-5 is a negative number!
192+
193+
بدیهی است که می‌توان کلاس‌های Exception خود را مطابق با میل خود پیاده‌سازی نمود:
194+
195+
.. code-block:: python
196+
:linenos:
197+
198+
class NegativeNumberError(Exception):
199+
"""Raised when the input value is negative number"""
200+
201+
def __init__(self, number, message="Number must be positive"):
202+
self.number = number
203+
self.message = message
204+
super().__init__(self.message)
205+
206+
def __str__(self):
207+
return f'ERROR[{self.number}] -> {self.message}'
208+
209+
210+
def plus(num):
211+
if num < 0:
212+
raise NegativeNumberError(num)
213+
214+
return num + num
215+
216+
217+
try:
218+
print(plus(10))
219+
print('*' * 30)
220+
print(plus(-5))
221+
222+
except NegativeNumberError as err:
223+
print(str(err))
224+
225+
except:
226+
print('Something bad happened!')
227+
228+
::
229+
230+
20
231+
******************************
232+
ERROR[-5] -> Number must be positive
233+
234+
235+
.. note::
236+
در زبان‌برنامه‌نویسی پایتون پیشنهاد می‌شود که اگر هدف از ایجاد Exception نمایش یک خطا باشد، در انتهای نام کلاس از واژه Error استفاده گردد.
237+
159238

160239
Context Manager و ``with``
161240
~~~~~~~~~~~~~~~~~~~~~~~~~~~

0 commit comments

Comments
 (0)