You are on page 1of 13

IST 603: Object-Oriented Programming with

Java and Python

Exceptions in Python
(From https://docs.python.org/3/tutorial/errors.html and other Sources)

Denis L. Nkweteyim

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 1


Outline

Syntax Errors vs Exceptions

Types of Exception

Exception Handling

Examples

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 2


Syntax Errors vs Exceptions

Syntax Errors

Caught at compile time

Example

Error detected at the print(function)

Missing colon(':') at the token preceding the arrow

while True print('Hello world')


File "/tmp/ipykernel_65413/2884618176.py", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 3


Syntax Errors vs Exceptions
x=5/0
Traceback (most recent call last): ●
Exceptions
File "/tmp/ipykernel_65413/1806623527.py", line 1, in <module>
x=5/0 ●
Errors detected during execution
ZeroDivisionError: division by zero
4 + spam*3

Type of exception (highlighted) is printed
Traceback (most recent call last): as part of the message
File "/tmp/ipykernel_65413/2481180859.py", line 1, in <module>
4 + spam*3

Exception type is the name of the built-in
NameError: name 'spam' is not defined exception that occurred
'2' + 2 ●
Preceding part of the error message
Traceback (most recent call last):
File "/tmp/ipykernel_65413/209420021.py", line 1, in <module>
shows the context where the exception
'2' + 2 occurred
TypeError: can only concatenate str (not "int") to str ●
In the form of a stack traceback
lst = [1,2,3]
print(lst[3])

In general it contains a stack traceback
Traceback (most recent call last): listing source lines
File "/tmp/ipykernel_74442/4045148883.py", line 1, in <module>
print(lst[3])

See
IndexError: list index out of range https://docs.python.org/3/library/exceptio
lst + 2 ns.html#bltin-exceptions
Traceback (most recent call last): for built-in exceptions
File "/tmp/ipykernel_74442/671147453.py", line 1, in <module>
lst + 2 03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 4
TypeError: can only concatenate list (not "int") to list
Python Exception Hierarchy

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 5


Handling Exceptions
while True: ●
The try statement
try:
x = int(input("Please enter a number: ")) ●
First, the try clause (the statement(s) between the
break try and except keywords) is executed.
except ValueError: ●
If no exception occurs, the except clause is
print("Oops! That was no valid number. Try again…") skipped and execution of the try statement is
finished
Please enter a number: x ●
If an exception occurs during execution of the try
Oops! That was no valid number. Try again... clause
Please enter a number: 5 ●
The rest of the try clause is skipped

Then, if its type matches the exception named after the
except keyword, the except clause is executed, and
then execution continues after the try/except block

If an exception occurs which does not match the
exception named in the except clause

It is passed on to outer try statements

If no handler is found, it is an unhandled exception and
execution stops with a message

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 6


Handling Exceptions
while True: ●
A try statement may have more than
try:
x = int(input("Please enter a number: "))
one except clause, to specify
break handlers for different exceptions
except (RuntimeError, TypeError, NameError): ●
At most one handler will be executed
Pass

Handlers only handle exceptions that
Please enter a number: x occur in the corresponding try
Traceback (most recent call last): clause, not in other handlers of the
File "/tmp/ipykernel_74442/1081471310.py", line same try statement
3, in <module>
x = int(input("Please enter a number: ")) ●
An except clause may name multiple
ValueError: invalid literal for int() with base 10: 'x' exceptions as a parenthesized tuple

Example with on the left has no
matching exception handler

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 7


Same example with a matching exception handler
while True:
try:
x = int(input("Please enter a number: "))
break
except (RuntimeError, TypeError, NameError, ValueError):
print("Oops! That was no valid number. Try again…")

Please enter a number: d


Oops! That was no valid number. Try again…
Please enter a number: 3

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 8


Raising Exceptions
raise NameError('Hi There') ●
Use the raise statement
Traceback (most recent call last): ●
You may need to determine whether an
File "/tmp/ipykernel_74442/2916444848.py", line 1,
in <module>
exception was raised but don’t intend to
raise NameError('Hi There') handle it
NameError: HiThere

try:
raise NameError('Hi There')

Or maybe we want to do something with
except NameError: an exception and then allow it to continue
print('An exception flew by!')
raise
to bubble up to the parent function, as if it
had never been caught?
An exception flew by!
Traceback (most recent call last): ●
Use a simpler form of the raise statement to
File "/tmp/ipykernel_74442/1282197570.py", line 3, re-raise the exception
in <module>
raise NameError('Hi There')
NameError: Hi There

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 9


Raising Exceptions II
def funny_division2(anumber): Testing 0: Enter a number other than zero
try: Testing hello: Enter a number other than zero
if anumber == 13: Testing 50.0: 2.0
raise ValueError("13 is an unlucky number") Testing 13: Traceback (most recent call last):
return 100 / anumber File "/tmp/ipykernel_74442/3165268737.py", line 3, in
except (ZeroDivisionError, TypeError): <module>
print(funny_division2(val))
return "Enter a number other than zero"
File "/tmp/ipykernel_74442/598231068.py", line 4, in
for val in (0, "hello", 50.0, 13): funny_division2
print("Testing {}:".format(val), end=" ") raise ValueError("13 is an unlucky number")
print(funny_division2(val)) ValueError: 13 is an unlucky number

def funny_division3(anumber): Testing 0: Enter a number other than zero


try: Testing hello: Enter a numerical value
if anumber == 13: Testing 50.0: 2.0
raise ValueError("13 is an unlucky number") Testing 13: No, No, not 13!
return 100 / anumber Traceback (most recent call last):
except ZeroDivisionError:
File "/tmp/ipykernel_74442/1153179225.py", line 3, in
return "Enter a number other than zero" <module>
except TypeError: print(funny_division3(val))
return "Enter a numerical value" File "/tmp/ipykernel_74442/4048255812.py", line 4, in
except ValueError: funny_division3
print("No, No, not 13!") raise ValueError("13 is an unlucky number")
raise ValueError: 13 is an unlucky number
for val in (0, "hello", 50.0, 13):
03/01/23 end=" ")
print("Testing {}:".format(val), Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 10
print(funny_division3(val))
Exception Chaining

Exception Chaining

Handling an exception that occurs inside an Except section
try:
open("database.sqlite")
except OSError:
print("Unable to open file")
raise RuntimeError("unable to handle error")
Unable to open file
Traceback (most recent call last):
File "/tmp/ipykernel_74442/2593180863.py", line 2, in <module>
open("database.sqlite")
FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/tmp/ipykernel_74442/2593180863.py", line 5, in <module>
raise RuntimeError("unable to handle error")
RuntimeError: unable to Denis
03/01/23 handleL. Nkweteyim@UB
error - IST603 (OO Prog - Exceptions in Python) 11
else and finally Clauses

We have already seen the try and except clauses, which
are mandatory for exception handling

else and finally are optional

Try: This block will test the excepted error to occur

Except: Here you can handle the error

Else: If there is no exception then this block will be executed

Finally: Finally block always gets executed whether
exception is generated or not

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 12


else and finally Clauses
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
except ZeroDivisionError:
print("Sorry, You are dividing by zero ")
else:
print("Your answer is :", result)
finally:
print('This is always executed')
divide(3,2)
Your answer is : 1
This is always executed

divide(3,0)
Sorry, You are dividing by zero
This is always executed

03/01/23 Denis L. Nkweteyim@UB - IST603 (OO Prog - Exceptions in Python) 13

You might also like