Lecture Notes #10
Errors & Exceptions
1
Errors in Python
▪ A Python program terminates as soon as it encounters an error. In
Python, an error can be either of these:
➢Syntax error
➢Exception
▪ Syntax errors occur when the parser detects an incorrect statement.
▪ An exception is an error that happens during execution of a program.
When that error occurs, Python generates an exception that can be
handled, which avoids your program to crash.
2
Syntax Errors
▪ If your code has syntax errors, it will not start running.
▪ Syntax errors are also known as parsing errors.
>>> a_string = "Hello'
File "<stdin>", line 1
a_string = "Hello'
^
SyntaxError: EOL while scanning string literal
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
3
Exceptions
▪ Even if a statement or expression is syntactically correct, it may
cause an error when an attempt is made to execute it.
▪ Errors detected during the program execution are called exceptions.
The last line of the error message indicates what type of exception
you ran into.
>>> 4 + 3*x >>> '2' + 2
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined TypeError: Can't convert 'int' object to str implicitly
>>> 10 * (1/0) >>> import engineer
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero ModuleNotFoundError: No module named 'engineer'
4
Built-in Exceptions
▪ There are many built-in exceptions in Python.
▪ You can also define your own exceptions, if needed.
▪ For a complete list of built-in exceptions, visit:
➢ https://docs.python.org/3/library/exceptions.html#bltin-exceptions
▪ Some examples (there are much more):
➢ Exception ➢ EOFError ➢ OSError ➢ SyntaxError
➢ ArithmeticError ➢ ImportError ➢ ReferenceError ➢ SystemError
➢ AssertionError ➢ LookupError ➢ RuntimeError ➢ TypeError
➢ AttributeError ➢ MemoryError ➢ StopIteration ➢ ValueError
➢ BufferError ➢ NameError ➢ StopAsyncIteration ➢ Warning
5
Built-in Exception Hierarchy
Note: This diagram does not
include all exception types.
6
Raising an Exception
▪ The raise keyword is used to manually raise (throw) an exception.
▪ Any type of exception can be raised.
▪ The statement can be complemented with a custom message.
▪ Raising an exception breaks current code execution and returns the
exception back until it is handled.
>>> raise TypeError >>> raise Exception("Something is very wrong!")
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <module>
TypeError Exception: Something is very wrong!
>>> >>>
7
Raising an Exception: Example
word = input("Please enter a word starting with 'a': ")
if not word.startswith("a"):
message = f"The word '{word}' does not start with 'a'."
raise TypeError(message)
print(f"You entered '{word}'.")
>>> word.py
Please enter a word starting with 'a': apple
You entered 'apple'.
>>> word.py
Please enter a word starting with 'a': orange
Traceback (most recent call last):
File "word.py", line 4, in <module>
raise TypeError(message)
TypeError: The word 'orange' does not start with 'a'.
8
Handling Exceptions
▪ When an error occurs, or exception as we call it, Python will stop
execution, generate an error message and terminate your program.
▪ Consider the following Python script:
# mylist.py
my_list = ["a", "b", "c", "d"]
z = my_list[4]
print(z)
>>> mylist.py
Traceback (most recent call last):
File "word.py", line 3, in <module>
IndexError: list index out of range
>>>
9
Handling Exceptions
▪ In Python, exceptions can be handled using
try and except statements.
try:
▪ A critical operation which could raise an statements
exception is placed inside the try block. ...
▪ The code that handles the exception is placed except:
statements
inside the except block. ...
▪ It is possible to write programs that handle all
or some selected exceptions.
10
Handling Exceptions
# mylist.py
my_list = ["a", "b", "c", "d"]
try: >>> mylist.py
z = my_list[4] Something's wrong.
print(z) >>>
except:
print("Something's wrong.")
>>> mynumber.py
# mynumber.py
Please enter a number: 7
while True:
You entered 7.
try:
>>> mynumber.py
x = int(input("Please enter a number: "))
Please enter a number: abc
print(f"You entered {x}.")
Oops! Try again...
break
Please enter a number: 10
except:
You entered 10.
print("Oops! Try again...")
>>>
11
Handling Specific Exceptions
def divide(x, y): >>> divide(7, 4)
try: The result is 1.75.
result = x / y
print(f"The result is {result}.") >>> divide(7, 0)
except TypeError: Cannot divide by zero.
print("Both x and y must be numbers.")
except ZeroDivisionError: >>> divide(7, "4")
print("Cannot divide by zero.") Both x and y must be numbers.
except:
print("Something else is wrong!") >>>
▪ The divide function will catch and handle all kinds of exceptions.
▪ It will execute specific and different lines of codes for TypeError and
ZeroDivisionError.
▪ If some other exception occurs, it will also be handled by the last except block.
12
Using else Blocks
▪ You can use the else keyword to define a block of code to be
executed if no errors were raised:
def divide(x, y): >>> divide(7, 4)
try: The result is 1.75.
result = x / y
except TypeError: >>> divide(7, 0)
print("Both x and y must be numbers.") Cannot divide by zero.
except ZeroDivisionError:
print("Cannot divide by zero.") >>> divide(7, "4")
except: Both x and y must be numbers.
print("Something else is wrong!")
else: >>>
print(f"The result is {result}.")
13
Using finally Blocks
▪ You can use the finally block to perform whatever actions need to
be executed afterwards even if there is an error or not:
def divide(x, y): >>> divide(7, 4)
try: The result is 1.75.
result = x / y Execution completed.
except TypeError:
print("Both x and y must be numbers.") >>> divide(7, 0)
except ZeroDivisionError: Cannot divide by zero.
print("Cannot divide by zero.") Execution completed.
except:
print("Something else is wrong!") >>> divide(7, "4")
else: Both x and y must be numbers.
print(f"The result is {result}.") Execution completed.
finally:
print("Execution completed. ") >>>
14
Summary of Exception Handling
try:
statements Execute this block as a normal part of the program.
... What your program actually intends to do
except:
statements Execute this block when there is an exception.
... There can be multiple except blocks with different exception types
else:
statements Execute this block only if no exceptions are raised.
... This block is optional
finally:
statements Always execute this block.
... This block is optional
15