Python/Examples

من موسوعة حسوب
اذهب إلى التنقل اذهب إلى البحث

هذه الصفحة هي تجميع منظم ومرتب لأمثلة بلغة بايثون

الاستثناءات

تحتوي هذه الفقرة على أمثلة يصدر فيها استثناءات.

الاستثناء FileNotFoundError

تُصدره بعض التوابع القارئة للملفات عند عدم وجود الملف

>>> f=open('D:\\file.txt')
		      
Traceback (most recent call last):
  File "<pyshell#123>", line 1, in <module>
    f=open('D:\\file.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\file.txt'

الاستثناء KeyError 

يصدر عند محاولة الوصول إلى عنصر عن طريق مفتاح غير موجود في القاموس

>>> a=dict()

>>> a["test"]="good"

>>> print(a["no key"])
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    print(a["no key"])
KeyError: 'no key'

الاستثناء ModuleNotFoundError

عند محاولة استيراد وحدة غير موجودة في المسار الافتراضي

>>> from stupid_module import *
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    from stupid_module import *
ModuleNotFoundError: No module named 'stupid_module'

الاستثناء NameError

عند محاولة استخدام متغير غير معرف مسبقًا.

>>> cache
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    cache
NameError: name 'cache' is not defined

الاستثناء NotImplementedError

عند استدعاء توابع معرفة على أنظمة POSIX وغير معرفة على ويندوز أو العكس

>>> Path('.').group()
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    Path('.').group()
  File "D:\Downloads\WinPython\python-3.6.5.amd64\lib\pathlib.py", line 1462, in group
    raise NotImplementedError("Path.group() is unsupported on this system")
NotImplementedError: Path.group() is unsupported on this system

الاستثناء OSError

يُرمى عند حدوث خطأ أثناء التعامل مع نظام التشغيل، كأن نحاول إنشاء ملف باسم لا يسمح له نظام التشغيل.

>>> open('D"\\test.txt').readlines()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    open('D"\\test.txt').readlines()
OSError: [Errno 22] Invalid argument: 'D"\\test.txt'

الاستثناء PermissionError

يُرمى عند محاولة الوصول إلى ملف، أو إنشاء ملف أو حذف ملف، دون أن يكون لمفسر بايثون الصلاحيات بالقيام بذلك

>>> open('C:\\file.txt','w')
		      
Traceback (most recent call last):


  File "<pyshell#105>", line 1, in <module>
    open('C:\\file.txt','w')
PermissionError: [Errno 13] Permission denied: 'C:\\file.txt'

الاستثناء UnicodeDecodeError

تحدث عند وجود كتابة بلغة غير الإنكليزية (باستخدام ترميز Unicode) وذلك عندما تستخدم تابع يتوقع قراءة ملفات بالإنكليزية حصرًا (أو بترميز utf-8)

في المثال التالي، فإن توابع الوحدة linecache مصممة لقراءة الملفات المصدرية لوحدات بايثون، وهي ملفات بالإنكليزية حصرًا.

>>> linecache.getline('D:\\file.txt',1)
		      
Traceback (most recent call last):
  File "<pyshell#116>", line 1, in <module>
    linecache.getline('D:\\file.txt',1)
  File "D:\Downloads\WinPython\python-3.6.5.amd64\lib\linecache.py", line 16, in getline
    lines = getlines(filename, module_globals)
  File "D:\Downloads\WinPython\python-3.6.5.amd64\lib\linecache.py", line 47, in getlines
    return updatecache(filename, module_globals)
  File "D:\Downloads\WinPython\python-3.6.5.amd64\lib\linecache.py", line 137, in updatecache
    lines = fp.readlines()
  File "D:\Downloads\WinPython\python-3.6.5.amd64\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 28: invalid continuation byte

الاستثناء ValueError

يُرمى عند تمرير وسيط غير صحيح القيمة للتابع.

>>> f=open('D:\\test.txt','w')

>>> f.close()

>>> print('Hello World!' , file=f)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    print('Hello World!' , file=f)
ValueError: I/O operation on closed file.

>>> f=open('D:\\test.txt','wa')
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    f=open('D:\\test.txt','wa')
ValueError: must have exactly one of create/read/write/append mode