Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách catch OSError Exception trong Python?

OSError đóng vai trò là error class cho module os, và được raise khi lỗi quay lại từ một os-specific function.

Chúng ta có thể viết lại code cho trước như sau để handle exception và biết type của nó.

# foobar.py
import os
import sys

try:
    for i in range(5):
        print(i, os.ttyname(i))
except Exception as e:
    print(e)
    print(sys.exc_type)

Nếu chúng ta chạy script này tại linux terminal:

$ python foobar.py

Chúng ta nhận được output sau:

OUTPUT

0 /dev/pts/0
1 /dev/pts/0
2 /dev/pts/0
3 [Errno 9] Bad file descriptor
<type 'exceptions.OSError'>