Skip to content

Exception (Error)

  • Exception means the python code occured any error, and python return an error message. (aka. Bug)

Example:

Python IDLE

py
>>> 1/0

Output: (error)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    1/0
    ~^~
ZeroDivisionError: division by zero

INFO

Example: ZeroDivisionError error message will return when any number divide by zero.

Error / Exception handling

When we facing error, normally one of these condition may happened.

  • Entire programme stop, returning an error message.
  • Returning an error message, but the programme still running.

So, error / exception handing, means that we assume that the code will returning error and caused entire programme stopped at some point. So we create a handler to handle this condition. It could be printing an error message on console but without stopping entire programme, or just telling the user that the system is error now, ...

Usage

Handling any type of error (catch-all)

Syntax

py
try:
    # The code may occured error


except Exception as e:
# or
# except:

    # Handle the error / e

error-handling-1.py

py
try:
    i = float(input("Enter the first number: "))
    j = float(input("Enter the second number: "))
    n = i / j
    print(n)

except:
    print(f"Failed to operate division")

Info

  • The default type of input() is str. We have to convert it to float.

Output: (i = 1, j = 2)

Enter the first number: 1
Enter the second number: 2
0.5

Output: (i = 1, j = 0)

Enter the first number: 1
Enter the second number: 0
Failed to operate division

INFO

except: will handle any kind of error, if no specific Error is mentioned.

except Exception as e: will also handle any kind of error, but allow us to know the error details by e.


Handling specific error

Means that it only can handle specific error, other than that will return error message.

Syntax

py
try:
    # The code may occured error
except Exception as e:
    # Handle the e kind of error only

INFO

Exception as e here will returning the error message details.

  • Example:
ZeroDivisionError: division by zero

Exception will be ZeroDivisionError.

e will return the error message - division by zero.

error-handling-2.py

py
try:
    i = float(input("Enter the first number: "))
    j = float(input("Enter the second number: "))
    n = i / j
    print(n)
    
except ZeroDivisionError as e:
    print(f"Failed to operate division")
    print(f"Error : {e}")

Output: (i = 1, j = 0)

Enter the first number: 1
Enter the second number: 0
Failed to operate division
Error : division by zero

Output: (i = 1, j = z) (error)

Enter the first number: 1
Enter the second number: z
Traceback (most recent call last):
  File "d:\jiale-note\demo-examples\Python\Language\error-handling-2.py", line 3, in <module>
    j = float(input("Enter the second number: "))
ValueError: could not convert string to float: 'z'

Handling multiple error

It's almost the same method like handling specific error. But the only changes here is from one Exception become a tuple of multiple Exception.

error-handling-3.py

py
try:
    i = float(input("Enter the first number: "))
    j = float(input("Enter the second number: "))

    n = i / j
    print(n)

except (ZeroDivisionError, ValueError) as e:
    print(f"Failed to operate division")
    print(f"Error: {e}")

Output: (i = 1, j = 0)

Enter the first number: 1
Enter the second number: 0
Failed to operate division
Error : division by zero

Output: (i = 1, j = z)

Enter the first number: 1
Enter the second number: z
Failed to operate division
Error: could not convert string to float: 'z'

Handling if no exception occured

error-handling-4.py

py
try:
    1 / 10

except Exception as e:
    print(e)

else:
    print("No error")

finally:
    # At this point, we can do file.close()
    print("Programme is about to close")

Output:

No error
Programme is about to close

Exception propagation 异常的传递

If all of the nested function unable to catch the error, the programme will return the error by default / stop the programme immediately

exception-propagation.py

py
# Define a function that has exception/error
def func1():
    print("f1 is running")
    num = 1 / 0
    print("f1 is ended")

# Define a normal function (no exception) and call the exception function
def func2():
    print("f2 is running")
    func1()
    print("f2 is ended")

def main():
    func2()

main()

Output: (Error)

  • A long-chain of the exception trace appeared.
Traceback (most recent call last):
  File "d:\jiale-note\demo-examples\Python\Language\exception-propagation.py", line 16, in <module>
    main()
    ~~~~^^
  File "d:\jiale-note\demo-examples\Python\Language\exception-propagation.py", line 14, in main
    func2()
    ~~~~~^^
  File "d:\jiale-note\demo-examples\Python\Language\exception-propagation.py", line 10, in func2
    func1()
    ~~~~~^^
  File "d:\jiale-note\demo-examples\Python\Language\exception-propagation.py", line 4, in func1
    num = 1 / 0
          ~~^~~
ZeroDivisionError: division by zero

Now, we add try-except:

py
# Define a function that has exception/error
def func1():
    print("f1 is running")
    num = 1 / 0
    print("f1 is ended")

# Define a normal function (no exception) and call the exception function
def func2():
    print("f2 is running")
    func1()
    print("f2 is ended")

def main():
    try:
        func2()
    except Exception as e:
        print(e)

main()

Output:

f2 is running
f1 is running
division by zero