Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Exception

Back


Try Except


Exception Handling


Raise an exception

print("\n--------raise--------\n")

x = -1
try:
    if x < 0:
        raise Exception("Sorry, no numbers below zero")
except Exception as ex:
    print(ex)           # Sorry, no numbers below zero

x = "hello"
try:
    if not type(x) is int:
        raise TypeError("Only integers are allowed")
except TypeError as ex:
    print("TypeError: {ex}".format(ex=ex))      # TypeError: Only integers are allowed
except Exception as ex:
    print("Exception: {ex}".format(ex=ex))

Customized Exception Class


class CustomizedException(Exception):
    print("inside")
    pass


try:
    raise CustomizedException()
except CustomizedException:
    print("Raised customized exception.")

# inside
# Raised customized exception.

With Statement

print("\n--------Example: with statement--------\n")

print("\n--------try except")
filename = "test.txt"


try:
    file = open(filename, 'r')
    try:
        content = file.read()
        print(content)
    except Exception as err:
        print(err)
    finally:
        file.close()
except FileNotFoundError as err:
    print(err)
else:
    print("success")


print("\n--------with statement")
try:
    with open(filename, 'r') as file:
        content = file.read()
        print(content)
except Exception as err:
    print(err)
else:
    print("success")


TOP