try
Clauseelse
Clausefinally
Clause
./ex20.py /usr/bin/python3^M bad interpreter: No such file or directory
dos2unix
which converts Windows text files into Unix text files
dos2unix FILENAME
>>> for = 5
File "<stdin>", line 1
for = 5
^
SyntaxError: invalid syntax
>>> name = "Glenn"
>>> print(nme)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'nme' is not defined
$ cat get_number_1.py
#! /usr/bin/python3
number = int(input("Number: ")
$ ./get_number_1.py
File "./get_number_1.py", line 6
^
SyntaxError: unexpected EOF while parsing
>>> for i in range(5):
... num = i * 2
... print(num)
File "<stdin>", line 3
print(num)
^
IndentationError: unindent does not match any outer indentation level
average = num_1 + num_2 / 2 print ('Average:', average)
$ ./file_open.py
Filename: xxxxxx
Traceback (most recent call last):
File "./file_open.py", line 6, in <module>
file = open(filename, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'xxxxxx'
$ ./file_open.py
Filename: unreadable.txt
Traceback (most recent call last):
File "./file_open.py", line 6, in <module>
file = open(filename, "r")
PermissionError: [Errno 13] Permission denied: 'unreadable.txt'
$ ./int_request.py
Integer: five
Traceback (most recent call last):
File "./int_request.py", line 5, in <module>
number = int(input("Integer: "))
ValueError: invalid literal for int() with base 10: 'five'
>>> round("five")
Traceback (most recent call last):
File "<stdin>, line 1, in <module>
TypeError: type str doesn't define __round__ method
$ ./divide_two_numbers.py
Numerator: 5
Denominator: 0
Traceback (most recent call last):
File "./divide_two_numbers.py", line 7, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero
try
/except
statement which has the following form
try:
STATEMENT
STATEMENT
...
except:
STATEMENT
STATEMENT
...
try
code block
execute normally unless a runtime error occurs
try
blockexcept
code block and executes those statementsopen
to create a file you should
put it inside a try
/except
statement
$ cat open_file.py #! /usr/bin/python3 # demonstrates using a try/except statement # to catch exceptions encountered while # trying to open a file filename = input("Filename: ") try: file = open(filename, "r") for line in file: print(line.rstrip()) except: print("Could not open file", filename) $ ./open_file.py Filename: xxxx Could not open file xxxx
for
loopinput
to ask the user for a numberinput
returns a string so we need to use a conversion functionint
and float
can cause a runtime errortry
/except
statementwhile
loopdef get_integer(): done = False while not done: number = input("Integer: ") try: number = int(number) done = True except: print(number, 'cannot be converted into an integer') return number
while
loop
True
insteadreturn statement to jump out of the loop when a value is OK
def get_integer(): while True: number = input("Integer: ") try: number = int(number) return number except: print(number, 'cannot be converted into an integer')
try
Clausefile = open('temps.txt', 'r')
$ ./temps_average_2.py Filename: xxx Traceback (most recent call last): File "./temps_average_2.py", line 7, in <module> file = open(filename, 'r') FileNotFoundError: [Errno 2] No such file or directory: 'xxx'
open
in the try
block
filename = input("Filename: ")
try:
file = open(filename, 'r')
except:
print('Cannot open', filename)
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
average = round(total/count, 2)
print('Average:', average)
$ ./temps_average_3.py Filename: xxx Cannot open xxx Traceback (most recent call last): File "./temps_average_3.py", line 15, in <module> for line in file: NameError: name 'file' is not defined
open
statement working for the rest of the script to worktry
block
filename = input("Filename: ")
try:
file = open(filename, 'r')
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
average = round(total/count, 2)
print('Average:', average)
except:
print('Cannot open', filename)
$ ./temps_average_4.py Filename: xxx Cannot open xxx
>>> open("xxx.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'xxx.txt'
file = open("test.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'test.txt'
>>> number = float(input("Number: ")) Number: five File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'five' >>> number = float(input("Number: ")) Number: 5..4 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: '5..4'
import
a module that doesn't exist
you get an ImportError object
>>> import foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'foo'
>>> print(5/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
def open_file_reading(): while True: filename = input("Filename: ") try: file = open(filename, "r") return file except: print("Cannot open", filename)
$ ./file_open_2.py
Filename: xxx
Cannot open xxx
Filename:
try
/except
statement
try:
STATEMENT
...
except:
STATEMENT
...
except
clauses for each exception object
try:
STATEMENT
...
except EXCEPTION_TYPE_1:
STATEMENT
...
except EXCEPTION_TYPE_2:
STATEMENT
...
...
def open_file_reading():
while True:
filename = input("Filename: ")
try:
file = open(filename, "r")
return file
except FileNotFoundError:
print("Cannot find", filename)
except PermissionError:
print("You do not have permission to read", filename)
$ ./file_open_3.py Filename: xxx Cannot find xxx Filename: unreadable.txt You do not have permission to read unreadable.txt Filename:
You do not have permission to read unreadable.txt
>>> open('xxx', 'r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'xxx'
except
header
except EXCEPTION_TYPE as VARIABLE:
def open_file_reading():
while True:
filename = input("Filename: ")
try:
file = open(filename, "r")
return file
except FileNotFoundError as err:
print(err)
except PermissionError as err:
print(err)
$ ./file_open_4.py Filename: xxx [Errno 2] No such file or directory: 'xxx' Filename: unreadable.txt [Errno 13] Permission denied: 'unreadable.txt' Filename:
except
block are called an
exception handler
else
Clausetry
/except
statement can also have an else
clausetry
block code does not
cause a runtime error
open
command fails
filename = input("Filename: ")
try:
file = open(filename, 'r')
except:
print('Cannot open', filename)
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
for
loop cannot work
try
code block
try:
file = open(filename, 'r')
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
average = round(total/count, 2)
print('Average:', average)
except:
print('Cannot open', filename)
else
clause
try:
file = open(filename, 'r')
except:
print('Cannot open', filename)
else:
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
average = round(total/count, 2)
print('Average:', average)
try
code block is meant to include code that
could cause a runtime error
try
clause
try
clause
except
clauseelse
clause
finally
Clausetry
/except
statement
finally:
STATEMENT
....
finally
clause will always be executedfinally
clause allows you to clean up any lose ends no matter
what happens when the script is run
I swear by Apollo Physician ... and by all the gods and goddesses ... I will use treatment to help the sick according to my ability and judgment, but never with a view to injury and wrong-doing.