İki tip arasında çok az fark vardır. Aslında, çekirdek Python geliştiricileri bile gerçek bir fark olmadığını kabul etti ve Python 3'te IOError
'u kaldırdı (şimdi OSError
için bir takma addır). PEP 3151 - Reworking the OS and IO exception hierarchy Bkz:
While some of these distinctions can be explained by implementation considerations, they are often not very logical at a higher level. The line separating OSError
and IOError
, for example, is often blurry. Consider the following:
>>> os.remove("fff")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'fff'
>>> open("fff")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'fff'
Evet, bu aynı hata mesajı iki farklı istisna türü bu.
Kendi kodunuz için OSError
numaralı atışı yapıştırın. Mevcut işlevler için belgelerini kontrol (o detay yakalamak için gereken gereken), ancak güvenle binebilirsiniz:
try:
# ...
except (IOError, OSError):
# handle error
tekrar PEP alıntı:
In fact, it is hard to think of any situation where OSError
should be caught but not IOError
, or the reverse.
* Değişik 3.3 sürümünde: ' EnvironmentError', 'IOError',' WindowsError', VMSError', socket.error', select.error' ve 'mmap.error'' OSError'’a birleştirilmiştir. “OSError” a at ve “IOError” un unutma. –
@MartijnPieters Teşekkürler, Python 2 etiketini ekledim. Sadece OSError'ı atmak bana iyi geliyor, ama ben her zaman shutil.copyfile() 'veya' os.access() 'gibi bir fonksiyonun IOError ya da OSError (her zaman yukarı bakmak zorunda kalması) anlamına geldiğinde ne zaman olduğunu bilmekte zorlanıyorum. –
Ayrıca, bu konuyla ilgili olarak https://www.python.org/dev/peps/pep-3151/ adresine bakın, iki istisnayı da perspektif haline getirmeye yardımcı olur. –