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

Cách catch IOError Exception trong Python?

IOError Exception

Là error raised khi input/output operation fails, như print statement hoặc hàm open() khi cố gắng open file không tồn tại. Nó cũng được raise cho operating system-related errors.

Nếu code cho trước được viết trong try block, nó raise input/output exception, được handle trong except block như sau:

Ví dụ

import sys

def whatever():
    try:
        f = open("foo.txt", 'r')
    except IOError as e:
        print(e)
        print(sys.exc_type)

whatever()

Kết quả

[Errno 2] No such file or directory: 'foo.txt'
<type 'exceptions.IOError'>