Python学習ノート(10):異常

3270 ワード

プログラムが実行されると、いくつかの異常現象が発生する可能性があります.これは存在する可能性があります.たとえば、ファイルを読むとき、そのファイルは存在しません.この場合、異常で処理できます.
1.エラー
簡単なテストをして、わざとprint方法をPrintに書きます.
>>> Print("Hello world")Traceback (most recent call last):  File "", line 1, in     Print("Hello world")NameError: name 'Print' is not defined>>>
システムはNameError異常を放出します.
2. try..except
tryを使ってもいいです.Exceptは異常を処理します.
try:

    f = open("test.txt")

    f.close()

except(IOError):

    print("The file is not exist.")

except:

    print("Some error occurred.")



print("Done")


実行結果:
The file is not exist.Done
3.異常発生
raise文で異常を引き起こすことができます.まずShortInputError例外をカスタマイズし、Exceptionクラスを継承する必要があります.
class ShortInputError(Exception):

    '''A user-defined exception class.'''

    def __init__(self, length, atleast):

        Exception.__init__(self)

        self.length = length

        self.atleast = atleast



try:

    s = input("Enter something -->")

    if len(s) < 3:

        raise(ShortInputError(len(s), 3))

    #Other work can continue as usual here

except(EOFError):

    print("Why did you do an EOF on me?")

except ShortInputError as e:

    print("ShortInputError: The input was of length %d, \

was expecting at least %d" % (e.length, e.atleast))

else:

    print("No exception was raised.")


2文字の実行結果を入力します.
>>> Enter something -->trShortInputError: The input was of length 2, was expecting at least 3>>>
3文字以上の実行結果を入力します.
>>> Enter something -->testNo exception was raised.>>>
4. try..finally
もしあなたがファイルを読むときに、異常が発生するかどうかにかかわらずファイルを閉じたい場合は、どうすればいいですか?これはfinallyブロックを使用して完了できます.1つのtryブロックの下で、except従文とfinallyブロックを同時に使用することができます.同時に使用する場合は、1つを別のものに埋め込む必要があります.
import time



try:

    f = open("poem.txt")

    while True: # our usual file-reading idiom

        line = f.readline()

        if len(line) == 0:

            break

        time.sleep(2)

        print(line),

finally:

    f.close()

    print("Cleaning up...closed the file")


実行結果:
>>> Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
Cleaning up...closed the file>>>
def divide(x, y):

    try:

        result = x/ y

    except ZeroDivisionError:

        print("Division by zero!")

    else:

        print("result is", result)

    finally:

        print("executing finally clause")


テスト結果:
>>> divide(2, 1)result is 2.0executing finally clause>>> divide(2, 0)Division by zero!executing finally clause>>> divide("2", "1")executing finally clauseTraceback (most recent call last):  File "", line 1, in     divide("2", "1")  File "", line 3, in divide    result = x/yTypeError: unsupported operand type(s) for/: 'str' and 'str'>>>