Learning Python

15. Exception handling

15.1. The basics about exceptions

#!/usr/bin/env python3

def main():
    try:
        print(x)
    except:
        print("An exception occurred")


if __name__ == "__main__":
    main()

Output:

An exception occurred
#!/usr/bin/env python3

def main():
    try:
        print(x)
    except SystemError:
        pass


if __name__ == "__main__":
    main()

Output:

Traceback (most recent call last):
  File "/workspaces/learning-python/test1.py", line 11, in <module>
    main()
  File "/workspaces/learning-python/test1.py", line 5, in main
    print(x)
NameError: name 'x' is not defined
#!/usr/bin/env python3

def main():
    x = 1
    try:
        print(x)
    except:
        print("System Error")
    else:
        print("Everything fine")


if __name__ == "__main__":
    main()

Output:

1
Everything fine
#!/usr/bin/env python3

def main():
    try:
        print(x)
    except:
        print("System Error")
    finally:
        print("The try-except works")


if __name__ == "__main__":
    main()

Output:

System Error
The try-except works

15.2. Raise an exception

#!/usr/bin/env python3

def main():
    x = 1
    y = 0

    if y == 0:
        raise Exception("Sorry, can not divide by zero")
    else:
        print(x/y)

if __name__ == "__main__":
    main()

Output:

Traceback (most recent call last):
  File "/workspaces/learning-python/test1.py", line 13, in <module>
    main()
  File "/workspaces/learning-python/test1.py", line 8, in main
    raise Exception("Sorry, can not divide by zero")
Exception: Sorry, can not divide by zero
#!/usr/bin/env python3

def main():
    x = 1
    y = "zero"

    if not type(y) is int:
        raise TypeError("Only integers are allowed")
    else:
        if y == 0:
            raise Exception("Sorry, can not divide by zero")
        else:
            print(x/y)

if __name__ == "__main__":
    main()
Traceback (most recent call last):
  File "/workspaces/learning-python/test1.py", line 16, in <module>
    main()
  File "/workspaces/learning-python/test1.py", line 8, in main
    raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed