Exceptions#

In general, two types of errors we can encounter in Python:

  • syntax error: also known as parsing error, the Python interprter cannot parse the codes to machine language.

  • exception: syntactically correct, cause an error when an attempt is made to execute the codes.

1. Syntax Error#

Syntax error is the most common complaint you get while you are still learning Python. This type of error is checked first before all other types of “Exceptions.” Following are some common examples:

  • In if statement, use assignment operator =, rather than comparison operator ==.

  • “if-else” statement without colon.

  • else without an if

  • define string with just one quote, or mixed single and double quotes.

  • mistyped dots e.g., 1.3.2

Tip

Can you identify the syntax error in the following code?

a = 3.4

if a = 3
    print("a is equal to 3")
elif:
    print("a is not equal to 3')

Note

Syntax error were checked first because Python Interpreter first converts Python code to machine code.

2. Exceptions#

Type Error

  • pass a list where a number or string is expected

  • more arguments received

int(['3.4'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10388\1844727562.py in <cell line: 1>()
----> 1 int(['3.4'])

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Name Error

  • A typo in Python keywords

  • A variable is called before it get defined

Zero Division Error

print(3 / 0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10388\1606758863.py in <cell line: 1>()
----> 1 print(3 / 0)

ZeroDivisionError: division by zero

Attribute Error

  • An object does not have the attribute called.m

"a".upper()
'A'
["a"].upper()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10388\1655869452.py in <cell line: 1>()
----> 1 ["a"].upper()

AttributeError: 'list' object has no attribute 'upper'

Value Error

  • Cannot convert something

  • useful when checking whether the input is numeric

float("3")
3.0
float("d")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10388\1603646997.py in <cell line: 1>()
----> 1 float("d")

ValueError: could not convert string to float: 'd'
num = input("Please enter a number: ")
print(float(num))

3. Exception Handling#

Customize the behavior when an exception occured. Using the try-except statement

try:
    some Python
    statements
except:
    what to do 
    if exception is raised
try:
    guess = int(input("Enter a number between 1 and 6: "))
except ValueError:
    print("Invalid number")