You are on page 1of 34

Nabeel Fahim

Home

Home  My courses  CS 1101 - AY2020-T5  6 August - 12 August  Discussion Forum Unit 8


 DISCUSSION ASSIGNMENT: UNIT 8

Search forums

Discussion Forum Unit 8


DISCUSSION ASSIGNMENT: UNIT 8
Settings Subscribe

  

The cut-o date for posting to this forum is reached so you can no longer post to it.

DISCUSSION ASSIGNMENT: UNIT 8


by Isaac Ayetuoma (Instructor) - Wednesday, 17 June 2020, 5:14 AM

Describe how catching exceptions can help with  le errors. Write three Python examples that
actually generate le errors on your computer and catch the errors with try: except: blocks. Include
the code and output for each example in your post. 

Describe how you might deal with each error if you were writing a large production program. These
descriptions should be general ideas in English, not actual Python code. 

68 words

Permalink

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Jonathan De Beer - Thursday, 6 August 2020, 4:37 AM

#There are a lot of types of le errors.


import os /
import errno
import io

import sys
dn, fn = 'foo', 'bar.txt'
pn = os.path.join(dn, fn)

def pre():
os.makedirs(dn, exist_ok=True)
open(pn, 'w').close()

def example1():
try:
os.mkdir(dn)
except OSError as e:
if e.errno != errno.EEXIST:
raise
else:
print('The directory already exitst')

def example2():
with open(pn, 'r') as inp:
try:
inp.write('test')
except io.UnsupportedOperation:
print('Can\'t change a readonly le')

def example3():
with open(pn, 'r') as inp:
old = sys.stdin
sys.stdin = inp
try:
text = input()
except EOFError:
print('Unable to read anything')
nally:
sys.stdin = old

def post():
# pn = 'aaa'
try:
os.remove(pn)
except:
/
i t( i f ()[1])
print(sys.exc_info()[1])
try:
os.rmdir(dn)

except:
print(sys.exc_info()[1])

def main():
try:
pre()
example1()
example2()
example3()
nally:
post()

#these are three examples of le errors


if __name__ == '__main__':
155 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Gbolahan Gadegbeku - Sunday, 9 August 2020, 8:23 PM

Nice work Jonathan. I observed you did not attached the results/output of your program as
well as how you will deal with the errors.
25 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Krista White - Monday, 10 August 2020, 12:00 PM

Hi Jonathan,
This is great, I learned some things from your post, which is good since the book didn’t
really teach us anything that would have allowed us to do this assignment justice. For
example, I learned the statement “makedirs”, which makes perfect sense but wasn’t a
command I was aware of before now. For your rst example, shouldn’t 'The directory
already exitst' come after ‘raise’? I thought the whole point of ‘raise’ was to raise a certain
error message.
80 words

Permalink Show parent

/
Re:Isaac
by DISCUSSION ASSIGNMENT:
Ayetuoma (Instructor) UNIT12
- Wednesday, 8 August 2020, 7:36 PM

Hello Krista,
Your observation concerning the textbook is correct, it is not all-encompassing,
especially, topics like les were not thoroughly explained there, notwithstanding,
going beyond the textbook to use relevant external resources is very much welcome.

Best,
Isaac Ayetuoma
39 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Enrique Gomez - Tuesday, 11 August 2020, 5:15 PM

Hello Jonathan. Good Work. I think this unit is complex and the text book gives us a brief
introduction to this topic. so you have research other kind of tools for this topic. Excelent.
34 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Richard Rugg - Wednesday, 12 August 2020, 6:03 PM

Great post Jonathan. I love your example of makedirs, so I certainly learned something
from your post. It would have been great to see the output examples, but keep up the
great work!
33 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Alessandro Galassi - Wednesday, 12 August 2020, 11:00 PM

Nice work, Jonathan. I tested these functions and they work, although I would have
preferred if you supplied the outputs aswell, but thats nothing major. well done!
27 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Enrique Gomez - Saturday, 8 August 2020, 1:52 PM

Describe how catching exceptions can help with le errors. Write three Python examples /
g p p y p
that actually generate le errors on your computer and catch the errors with try: except:
blocks. Include the code and output for each example in your post.

According to Downey, A. (2015) Some errors appears when you try to read or write les, such as
trying to open a le that don´t exist, to open a le you have not the permission or try to open a
directory for reading. In this cases python has some options to avoid these errors. for example
os.path.exists and os.path.is le, but this options requires a lot of time and code, and nding an
error could be a tedious activity. To solve this issue, we can use a try clause that contain a
except clause, which runs when an exception occurs. The result of this clause is an error
message that give us the possibility to x the problem or try again. It is called catching an
exception.
------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
#FILE DOES NOT EXIST
n=open("Test2.txt")
------------------------------------------------
OUTPUT
FileNotFoundError Traceback (most recent call last)
in
----> 1 n=open("Test2.txt")

FileNotFoundError: [Errno 2] No such le or directory: 'Test2.txt'

------------------------------------------------
CATCHING ERROR
try:
n=open("Test2.txt")
except:
print("File do not exist")

OUTPUT
File do not exist
------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
#OPEN A DIRECTORY FOR READING
n=open("C:\\Users\\enrique.gomez\\")
------------------------------------------------
OUTPUT
FileNotFoundError Traceback (most recent call last)
in
1 #OPEN A DIRECTORY FOR READING
2
/
3 ("C \\U \\ i \\")
----> 3 n=open("C:\\Users\\enrique.gomez\\")

FileNotFoundError: [Errno 2] No such le or directory: 'C:\\Users\\enrique.gomez\\'

------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
CATCHING ERROR
try:
n=open("\\Users\\enrique.gomez\\")
except:
print("Trying to open a directory for reading")
OUTPUT
Trying to open a directory for Reading
---------------------------------------------------------------------------------------------------------------------
#CREATE A FILE THAT ALREADY EXISTS
f = open("output.txt", "x")
OUTPUT
FileExistsError Traceback (most recent call last)
in
----> 1 f = open("output.txt", "x")

FileExistsError: [Errno 17] File exists: 'output.txt'


------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
CATCHING ERROR
try:
n = open("output.txt", "x")
except:
print('Creating a le that already e')
OUTPUT
Creating a le that already exists
------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------

Describe how you might deal with each error if you were writing a large production
program. These descriptions should be general ideas in English, not actual Python code.

I will use the some suggestions from  Downey, A. (2015):

Check the Preconditions: Preconditions are the responsibility of the caller. If the caller violates
a precondition and the function don’t work correctly, the bug is in the caller.

Check the Postconditions: if there is something wrong with the function; a postcondition is
/
i l t d If th diti ti d d th t diti t th b i i id th
violated. If the preconditions are satis ed and the postconditions are not, the bug is inside the
program

Check the Program: Place in the middle of the program or where or in a place where there
might be errors, a print statement or something that has a veri able e ect. If a problem
appears it is mean that a trouble exists in the rst half of the program. It the problem don’t
appear in this section go to next section to place another print statement to verify values or
actions. In this way a big program can be debugged more e cient than checking line by line.
This is called debugging by bisection.

                                                                                                                      REFERENCES
Downey, A. (2015). Think Python, How to think like a computer scientist. This book is licensed
under Creative Commons Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0)
561 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Gbolahan Gadegbeku - Sunday, 9 August 2020, 8:27 PM

Great work Gomez, I like all the above examples you cited in your work and the way you
will deal with each error.
23 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Krista White - Monday, 10 August 2020, 12:20 PM

Hi Enrique,

Good job. In your line "f = open("output.txt", "x")", what does the "x" part do? We learned
what 'w' does in that position, but not 'r' (which seems kind of essential), and de nitely not
'x'.
38 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Enrique Gomez - Tuesday, 11 August 2020, 5:12 PM

If you need to create a le "dynamically" using Python, you can do it with the "x"
mode.

Modes available are: /


Read ("r").
Append ("a")
Write ("w")
Create ("x")

REFERENCES

https://www.freecodecamp.org/news/python-write-to- le-open-read-append-and-
other- le-handling-functions-explained/
36 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Troycie Celestine - Monday, 10 August 2020, 12:40 PM

Excellent post here. You have provided explanations as you went along with the great
examples provided. I really like the conclusion area on how to deal with an error, you were
very thorough.
33 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Ndumiso Mkhize - Tuesday, 11 August 2020, 1:55 AM

Hi Enrique

Thank you for your explanation on the subject of catching exceptions, i was also
wondering about your last example as well about the "x" as i only came across, 'r' for read,
'w' for write, 'a' for appending and 'r+' for read and write, what would the 'x' designation be
for in ling?

Good and insightful post and easy to understand, thank you.


65 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Enrique Gomez - Tuesday, 11 August 2020, 5:13 PM

Hi Ndumiso

If you need to create a le "dynamically" using Python, you can do it with the "x"
mode. /
Modes available are:
Read ("r").
Append ("a")
Write ("w")
Create ("x")

REFERENCES

https://www.freecodecamp.org/news/python-write-to- le-open-read-append-and-
other- le-handling-functions-explained/
38 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Ndumiso Mkhize - Wednesday, 12 August 2020, 5:44 AM

Thank you Enrique

That is very informative.


7 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Vernon Tembo - Tuesday, 11 August 2020, 4:43 PM

Hello Enrique Gomez


Once again you have fully explained the weeks task with excellence. I have learnt
something.
Good Job and all the best on your exams
27 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Richard Rugg - Wednesday, 12 August 2020, 6:05 PM

Enrique, as always this is an amazing post, very well detailed with great examples. I always
learn something from your posts, this time I learned about the "x" mode to create a le.
Keep up the great work as always.
40 words

Permalink Show parent


/
Re: DISCUSSION ASSIGNMENT: UNIT 8
by Alessandro Galassi - Wednesday, 12 August 2020, 11:00 PM

Well done, Gomez!


3 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Gbolahan Gadegbeku - Saturday, 8 August 2020, 3:07 PM

My 3 examples:
1. Input:
# Program to handle multiple errors with one except statement
try :
a=2
if a < 3 :

# throws ZeroDivisionError for a = 2


b = a/(a-2)

# throws NameError if a >= 3


print("Value of b = ", b)

# note that braces () are necessary here for multiple exceptions


except(ZeroDivisionError, NameError):
print ("\nError Occurred and Handled")
Output:
=== RESTART: C:/Users/Oamos/AppData/Local/Programs/Python/Python38-32/test.py ==

Error Occurred and Handled


>>> 2. Input:
try:
fh = open("result le", "r")
fh.write("This is my result le for exception handling!!")
except IOError:
print("Error: can\'t nd le or read data")
else:
print("Written content in the le successfully")
Output:
=== RESTART: C:/Users/Oamos/AppData/Local/Programs/Python/Python38-32/test.py ==
Error: can't nd le or read data
>>> 3. Input:
/
# A simple runtime error
# A simple runtime error

a = [2,4,5]

try:
print("Second element = %d" %(a[2]))

# Throws error since there are only 3 elements in array


print("Fourth element = %d" %(a[5]))

except IndexError:
print("An error occurred")
Output:
=== RESTART: C:/Users/Oamos/AppData/Local/Programs/Python/Python38-32/test.py ==
Second element = 5
An error occurred
>>> Part 2:
How I will deal with the error in large production program:
1. I will code in easy and understandable syntax.
2. I will ensure checkpoints in my program while coding
3. By using block-level approach when errors occur in my program.
225 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Krista White - Monday, 10 August 2020, 12:27 PM

Hi Gbolahan,

I learned things from your post, which as stated above is good because I don't feel like the
book really covered anything of substance on this subject. So when you write "except
IOError:", does that mean we have to specify the TYPE of error we might be expecting? I
thought it was just if ANY error occurred, then it would follow the except path, but maybe
this is a way of being more speci c. That would be nice.
80 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Richard Rugg - Wednesday, 12 August 2020, 6:06 PM

Great post Gbolahan, I really like how you outlined the IOError exception as a way to
narrow down the exception. Keep up the great work.
25 words
/
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Alessandro Galassi - Wednesday, 12 August 2020, 11:01 PM

Nice work, Gbolahan.


3 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Elad Tenenbom - Saturday, 8 August 2020, 5:32 PM

Catching exceptions is a useful and fast solution when trying to get access to les in the le
system.

Since we are talking about di erent systems many errors may occur, wrapping the code with try
except block is a fast and good looking solution, but of course it is not recommended because
the interpreter is working hard when collapsing.,

Instead, it's better wrap the code with if statements with conditions such as "is le exist","is
path permitted" etc.

In a large production program I might open les from a permitted database or receive content
from known API, and try to avoid dealing with the local le system as I can.

After a few trials, I generated 2 errors in my computer, I couldn't nd a third example, with a
di erent error message than the rst two.

code and output attached below.

142 words

/
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Gbolahan Gadegbeku - Sunday, 9 August 2020, 8:29 PM

Elad great job. I love your explanation above and how you keep your work simple and
precise.
17 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Ndumiso Mkhize - Tuesday, 11 August 2020, 1:58 AM

Hi Elad

Thank you for throwing more light into this subject with your examples, i was trying to
follow as much as i can from the course book but kept getting confused with some
aspects, so thank your for simplifying especially for this discussion.
44 words

Permalink Show parent


/
Re: DISCUSSION ASSIGNMENT: UNIT 8
by Vernon Tembo - Tuesday, 11 August 2020, 4:48 PM

Good day Enrique Gomez


great and simple explanations accompanied with examples which are easy to understand.
good job and best of luck during the nal exam
26 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Abdulaziz Idris Abubakar - Wednesday, 12 August 2020, 8:13 AM

Great work Elad and very easy to understand.


8 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Nabeel Fahim - Wednesday, 12 August 2020, 11:22 PM

Hello Elad Tenenbom,

This part:
except BaseException as e:
print('something went wrong: '+str(e))

was a very helpful thing, I tried to do the same but could not gure our how. Your post
includes everything required except for what you yourself mentioned: Example 3. In that
regard, you can use something like these as well:

try:
    n = open('Nex_text.txt', 'r')
except IsADirectoryError:
   print("It is a directory and not a le")
except FileNotFoundError:
   print("File could not be found")
except PermissionError:
   print("Access Denied")
except NameError:
   print("It has to be a le or refer to a le. As it is now, it is not de ned")

As for arguments, you can pass on unde ned variable, directory path instead of le name,
or le with passwords that are restricted for writing. Best wishes for the upcoming exams.
/
BR
140 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Ndumiso Mkhize - Sunday, 9 August 2020, 6:28 AM

The try and except blocks allows the program to test out a piece of code and if all is correct
and there are no bugs or errors the program will continue to run and if there is an error within
the block of code the except block will let you know (through printing an error you speci ed for
the except block) and lets you handle that error.

Not De ned Error - exception when the variable or name is not de ned in the code

code
print(code)

Output:
Traceback (most recent call last):

  File "/Users/PycharmProject/Workboard CS1011/Practice.py", line 1, in <module> code

NameError: name 'code' is not de ned

# Using the try and except block to catch exceptions for the above code.

try: # Using the try block to catch the error


print(code)
except: # Catches the wrong part of the code and alerts to
the error
print("Name not defined")

Output:
Name not de ned                # Since the code has an error the except block will be executed.  

Division by Zero - in mathematics division by zero is not allowed and so the same in
Python as a formal language 

div = 5/0
print(div)

Output:

  File "/Users/PycharmProject/Workboard CS1011/Practice.py", line 1, in <module>

    div = 5/0

ZeroDivisionError: division by zero

# Using the try and except block to catch exceptions for the above code. /


# Using the try and except block to catch exceptions for the above code.

try:
div = 5/0
print(div)
except:
print('ZeroDivisionError')

Output:
ZeroDivisionError

Value error - an error that could be caused by entering a wrong type of data in this case a
str instead of an int

num = int('hello world')


print(num)

Output:
  File "/Users/PycharmProject/Workboard CS1011/Practice.py", line 1, in <module>

    num = int('hello world')

ValueError: invalid literal for int() with base 10: 'hello world'

# Using the try and except block to catch exceptions for the above code.

try:
num = int('hello world')
print(num)
except:
print('ValueError')

Output:
ValueError

Catching exceptions helps with le errors in that instead of breaking the code completely, by
having the try and except blocks it keeps the code in "control" with the errors that might be in
the code and the programmer is able to identify the errors and lets him/her handle and x
them without crashing or breaking the entire code where there is an error, which is very helpful
when you have a large program. Also when you are writing a large program you can write  try
and except blocks that have code to catch speci c types of errors for example, (except
ValueError:) or (except ZerroDivisonError:) and (except NameError) so that within that long code
you can clearly identify what is the source of error(s) raised making it easier to debug the
program.

441 words
/
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Vernon Tembo - Tuesday, 11 August 2020, 4:51 PM

Good day Ndumiso Mkhize


You never disappoint with your post always on point. Very informative post this week.
Great job
20 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Abdulaziz Idris Abubakar - Wednesday, 12 August 2020, 8:12 AM

Hi Ndumiso,
As always I like going through your post because You enclose meaningful explanation on
your codes. Great work!
20 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Troycie Celestine - Sunday, 9 August 2020, 11:26 AM

Errors and Exceptions result in a code unable to be run properly. Errors, like Syntax or runtime
errors, are common errors, usually occurring for a simple reason such as the missing of a : or "
when required. Exceptions are essentially errors that are not unconditionally fatal, resulting
from something like a zero division error or a Name Error (Downey, 2015). You will know which,
as when the execute fails, you will see a note for a Syntax error or speci c exception like Zero
Division Error. To make life easier on oneself as they attempt to execute code, they can catch
exceptions by utilize try or except as a way of handling the issues as they come.

#Division Error Example

/
#Division error with try and except

/
Reference

Downey, A. (2015). Think Python, how to think like a computer scientist, 2nd Edition.
139 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Ndumiso Mkhize - Tuesday, 11 August 2020, 2:07 AM

Hi Troycie
/
Well written post and easy to follow with good examples. I like your last example explains
well how the try and except block could be used in a longer program as instead of

breaking the code and just giving you an error, because of the try and except block in the
code it was able to still run the code until the except block was executed.

Good work Troycie


71 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Mafrikhul Muttaqin - Sunday, 9 August 2020, 10:03 PM

Error, where something in the program goes wrong, may appear in various situations. By using
the exception, the Phyton interpreter stops the process and passed it to another process until it
successfully handled.

# Example 1
1. a. Generating Error
a = 2
b = 0
c = a / b
print(c)
Output :
Traceback (most recent call last):
 File "<string>", line 5, in <module>
ZeroDivisionError: division by zero
1. b. Using Exception
x = 1
y = 0
try:  
    z = x / y
    print (z)
except ZeroDivisionError:  
    print("'zero division error' found, 'y' should not be zero" )
else:  
    print("nice, no error found")
Output :
'zero division error' found, 'y' should not be zero

/
Example 2
2. a. Generating Error
weapon_dictionary = {"Luffy" : "rubber", "Zorro" : "sword" , "Sanji" : "leg"
, "Nami" : "weather" }
print(weapon_dictionary["Lufy"])
Output :
Traceback (most recent call last):
   File "<string>", line 29, in <module>
KeyError: 'Lufy'
2. b. Using Exception
try:
    weapon_dictionary = {"Luffy" : "rubber", "Zorro" : "sword" , "Sanji" : "l
eg" , "Nami" : "weather"}
    print(weapon_dictionary["Lufy"])
except KeyError:
    print("'key error' found, try the right name")
else:
    print("nice, no error found")
Output :
'key error' found, try the right name

Example 3
3. a. Generating Error
crew_name = ["Luffy" , "Zorro" , "Sanji"]
print(crew_name[3])
Output :
Traceback (most recent call last):
 File "<string>", line 48, in <module>
IndexError: list index out of range
3. b. Using Exception
try:
    crew_name = ["Luffy" , "Zorro" , "Sanji"]
    print(crew_name[3]) 
except IndexError:  
    print ("'index error' found, try the right range")
else:  
    print ("nice, no error found")
Output :
'index error' found, try the right range

How to deal with errors in a large production program?

First, I think for the purpose of reducing any errors or bugs that appeared in the program, the
program itself should be well written. The code writer should have enough knowledged
background of coding as well as some delity and patience. For working in a group, in addition
to the code writer characteristics, I may suggest for making some working logs for error or bug
tracing easier.  

Then, we should understand the di erences between errors and exceptions as well as the /
Then, we should understand the di erences between errors and exceptions as well as the
correct ways to handle them (Filip, 2017). By doing so, we can take a proactive approach before
the error appeared. Simply to say, in a program, we should prepare the code of exception for

any error that appeared caused by user input. 

Reference

Filip. (2017). How to handle errors and exceptions in large scale software projects (With good
practices and examples). Retrieved from https://raygun.com/blog/errors-and-exceptions/

393 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Troycie Celestine - Monday, 10 August 2020, 12:35 PM

This is a very thorough discussion post and looks to have great explanations and solid
examples.
16 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Khai Lamh Cin - Wednesday, 12 August 2020, 4:02 AM

Hi Muttaqin,
That was a clear ocnsense post, got more deep into the topic from yours.
Thanks
17 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Abdulaziz Idris Abubakar - Wednesday, 12 August 2020, 8:08 AM

Hi Muttaqin,
your codes are correct and you provided more explanations for everyone to understand
and I like the style of your presentation.
23 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Isaac Ayetuoma (Instructor) - Wednesday, 12 August 2020, 7:39 PM

Hello Mafrikhul,
/
Th t f l ti l d di f d S El d' tf id
The concept of le was not included in any of your codes. See Elad's post for a guide.

Best regards,
Isaac Ayetuoma
24 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Abdulaziz Idris Abubakar - Monday, 10 August 2020, 6:04 AM

Discussion Forum Unit 8


CS 1101 - AY2020-T5
August 10, 2020

>>> try:
. . . x = 10 / 0
. . . except:
. . . print(“ZeroDivisionError”)
...
ZeroDivisionError
>>> #Even though both 10 and 0 are integer but 10 cannot be divided by 0 therefore we get
division error.
>>> try:
. . . y == 5
. . . except:
print(“NameError”)
...
NameError
>>> The name y is not de ned therefore, we get name error.

>>> try:
. . . “12” – 2
. . . except:
. . . print(“TypeError”)
...
TypeError
>>> #Here the output is type error because “12” is string and 2 is an integer therefore, they
don’t belong to the same type.
In order to deal with these errors there is need to lter all the input data because the errors
occur as a result of wrong input.
112 words

/
Permalink Show parent
Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Khai Lamh Cin - Wednesday, 12 August 2020, 4:00 AM

Hi Abubakar,
What if we use more on les errors and what if we are working on a production level
development ?
Thank you
23 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Abdulaziz Idris Abubakar - Wednesday, 12 August 2020, 8:05 AM

Hi Khai,
I don't understand your question.
7 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Krista White - Monday, 10 August 2020, 9:43 AM

Catching exceptions can help with le errors by virtue of the fact that that is what they are
designed to do. The downside is that the programmer has to anticipate the errors; they can
only be caught if they are anticipated and exceptions are provided that work.

#Catching exception of not being in the expected directory.

#In a large organization I would encourage people to

#save les in the appropriate, designated locations.

try:

    open('test_ le.txt')

except:

    open('C:\\User\\my les\\test_ le.txt')

#Catching exception of le not having been opened in write mode.

#I would deal with this probably by just writing code to open /


#the le always in write mode, rather than letting the user

#open it.

try:

    le.write('Summary page')

except:

    le.close

    open(' le.txt','w')

    le.write('Summary page')

#Catching exception of user not entering a valid directory name.

#I might deal with this by giving the user a list of valid

#directory names and having them pick one from the list.

try:

    import os

    os.listdir(input('Give me a directory'))

except:

    import os

    print('That''s not a directory name. Your current working directory''s les are:')

    os.listdir(cwd)

198 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Khai Lamh Cin - Wednesday, 12 August 2020, 3:58 AM

Hi Krista,
that was a nice description, thank you
9 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Vernon Tembo - Tuesday, 11 August 2020, 4:19 PM

Some of the le errors that can be encountered are le does not exist error (trying to open a
le that does not exist) and permission error (trying to open a le without permission), /
le that does not exist) and permission error (trying to open a le without permission),
(Downey, 2015).
#this code will generate a le does not exist error

examp1=open('unit8.txt')
print (examp1)
Output
Traceback (most recent call last):
File "C:\Users\Vernon Tembo\Desktop\UNIT 8 TESTS.py", line 2, in
examp1=open('unit8.txt')
FileNotFoundError: [Errno 2] No such le or directory: 'unit8.txt'
>>>
#this code will generate a permission error
import os
y=os.getcwd()
examp2=open(y)
print (examp2)
Output
Traceback (most recent call last):
File "C:\Users\Vernon Tembo\Desktop\UNIT 8 TESTS.py", line 4, in
examp2=open(y)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Vernon Tembo\\Desktop'
>>>
#the following codes indicate how these catch these exceptions
try:
examp1
except:
print ('oh no dear the le does not exist')
Output
oh no dear the le does not exist
>>>
try:
examp2
except:
print ('you dont have permision')
Output
you dont have permision
>>>
To deal with these le errors in large programs, it best to for check them. For example
>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('/home/dinsdale')
True
REFERENCE
/
Downey, a. (2015). Think python: how to think like a computer scientist. Needham,
Massachusetts: green tree press.

223 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Khai Lamh Cin - Wednesday, 12 August 2020, 3:57 AM

Hi Tembo,

Got got get some more depth into the topic from your post, catching exceptions are the
very useful things in Python where we could have some custom messages for those errors.
Awsome and Thanks
36 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Nabeel Fahim - Wednesday, 12 August 2020, 11:14 PM

Hi Vernon Tembo

You have a very good understanding I see. However, I think you should have addressed
the second part of the requirement as well. While, that was a small shortcoming, your
discussion and explanation on the error types and adding exception to handle these
errors were very easy to understand. Thank you!

BR
55 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Khai Lamh Cin - Wednesday, 12 August 2020, 3:05 AM

Catching exceptions can help with le errors by producing speci c error message to the
program user to be able to understand the error easily and try on the xes.  

/
Example (1)
>>> def file_error(a):
... try:
... file = open(a)
... except NameError: #(Python Software Foundation, 2019)
... print(
... 'Filename error')
... except FileNotFoundError: #(Python Software Foundation, 2019)
... print('your file not found')
...
>>> file_error('C:\\Users\\HP\\Documents\\CS1101\\words.txt')
>>> file_error('C:\\Users\\HP\\Documents\\CS1101\\words.tx')
your file not found
>>> file_error('C:\\Users\\HP\\Documents\\CS1101\\words')
your file not found

Example (2)
>>> import os
>>> def rename_error(a):
... try:
... os.rename(a)
... except PermissionError: #(Python Software Foundation, 2019)
... print("you have not enough permission to edit this file")
... except TypeError: #(Python Software Foundation, 2019)
... print("there is something wrong with the code")
...
>>> rename_error('C:\\Users\\HP\\Documents\\CS1101\\words.txt')
there is something wrong with the code
>>>

/
Example (3)
>>> def create_file_error(a):
... try:
... status = os.path.exists(a)
... if status == False:
... open(a, 'w')
... else:
... print('status = '+status)
... except:
... print('You got something wrong with your program')
...
>>> create_file_error('words.txt')
You got something wrong with your program
>>> create_file_error('text.txt')
>>> os.system('dir')
Volume in drive C has no label.
Volume Serial Number is 4044-D496

Directory of C:\Users\HP\Documents\CS1101

12-Aug-20 02:30 PM <DIR> .


12-Aug-20 02:30 PM <DIR> ..
12-Aug-20 02:23 PM 0 a
12-Aug-20 02:06 PM 0 a.txt
06-Aug-20 11:29 PM <DIR> P-1
09-Aug-20 01:42 AM <DIR> P-2
10-Aug-20 05:27 PM <DIR> P-3
31-Jul-20 02:07 AM 814,210 TEXT - Think Python 2e.pdf
12-Aug-20 02:30 PM 0 text.txt
12-Aug-20 02:24 PM 0 words.txt
5 File(s) 814,210 bytes
5 Dir(s) 125,689,384,960 bytes free
0
>>>

As found in the above examples, we could write some mulitiple error messages by catch up
multiple Python built-in error codes and if this is a production development, I will try to catch all
the possible errors at one and gure out if Python provides built-in error code for those kind of
error and will create a single error message function within the program where it would be
avalible for the future requirement of changs. 

References:

Python Software Foundation. (2019, June 16). Built-in Exceptions. Python.


https://docs.python.org/3.4/library/exceptions.html

/
392 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Alessandro Galassi - Wednesday, 12 August 2020, 6:24 AM

Explanation:

Catching an exception can be helpful with le errors and in general, because it gives you a
chance to x the problem, try again or end the program gracefully. 

Reference:
Downey, A. (2015). Think Python How to Think Like a Computer Scientist. Needham,
Massachusetts: Green Tea Press. Retrieved from
http://greenteapress.com/thinkpython2/thinkpython2.pdf

Examples:
1)

#Catching an exception with Type Error

>>> try:
x = 5
y = '0.3'
print(x + y)
except TypeError:
print('WrongType')
WrongType

2)

#Catching an exception with Name Error

>>> try:
string = 'woopdeedoo'
print(string+bling)
except NameError:
print('WrongName')
WrongName

3)

#Catching an exception with Zero Division Error

/
>>> try:
num = (55+45)
num2 = 0
print(num/num2)
except ZeroDivisionError:
print('ZeroDivError')
ZeroDivError

Description:

Checking for le errors prior to program execution may help.

128 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Nabeel Fahim - Wednesday, 12 August 2020, 11:10 PM

Hello Alessandro

Really appreciate your sincere e orts. Your codes imply that you have good understanding
of the concepts, but I think you did not properly understand the requirement of this
discussion post. If you re-read carefully, "Describe how catching exceptions can help with
le errors." is the requirement. But in your examples, le error handling examples are
absolutely absent. Wish you all the success in the coming exam.

BR
69 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Richard Rugg - Wednesday, 12 August 2020, 5:39 PM

Code:
try:
    open('nonexistent_ le')
except:
    print('ERROR: File Does Not Exist')
/
try:
    open('/etc/usr', 'w')
except:
    print('ERROR: Permission Denied')

try:
    open('/')
except:
    print('ERROR: Cannot Open Directory')

Output:
"/Applications/Python 3.8/IDLE.app/Contents/MacOS/Python"
/Users/rjrugg/PycharmProjects/UoP-CS1101-RR/unit8-discussion.py
ERROR: File Does Not Exist
ERROR: Permission Denied
ERROR: Cannot Open Directory
 
Process nished with exit code 0

Use Description:
For the rst and third examples, if the use case was a user-de ned le (maybe from input), I
would display the error and make a call back to the function that was prompting for the input
again, to allow the user to de ne another le. For the second example, I would potentially  build
in a "fail-safe" le that could be written to, accompanied by an error identifying that permission
was denied, and a default le was used to write the output.

142 words

Permalink Show parent

Re: DISCUSSION ASSIGNMENT: UNIT 8


by Nabeel Fahim - Wednesday, 12 August 2020, 10:54 PM

/
Catching exceptions in File errors can help debugging a lot easier, especially if we know kind
of error it is. For example, I included few possible error types that may arise while coding to
read, write or open a le. Handling these errors can not only help gure out the mistakes but
can also help with proceeding with the rest of the codes. 

In this instance, I actually added few comments for myself if I make any mistakes. In rst
example, I wanted to write a le, however the parameter I provided was a directory and not a
speci c le name. If I go ahead with the mistakes, an error will be triggered with symbols like
Errorno 2 or something. However, as I put it in exception handling, I can exactly gure out the
mistakes and rectify it for the code to work awlessly. 

While writing a large production program, I would put extra attention to the following few
aspects in order to avoid errors and bugs:

Use try and exception blocks in critical parts that are likely to trigger errors. This will not
only help me handle the errors, but will also help me rectify them later on.
Use print statement to print out exact instances to understand the nature of error better.
Generalize codes so save space and confusion.
Use debugging tools more often so that I might not get overwhelmed in nding an
untraceable error.

238 words

Permalink Show parent /


◀ Learning Guide Unit 8
Jump to...

Learning Journal Unit 8 ▶

 UoPeople Clock (GMT-5)

All activities close on Wednesdays at 11:55 PM, except for Learning Journals/Portfolios which close
on Thursdays at 11:55 PM always following this clock.

Wed, Aug 19, 2020


9:05 pm

Disclaimer Regarding Use of Course Material  - Terms of Use


University of the People is a 501(c)(3) not for pro t organization. Contributions are tax deductible to
the extent permitted by law.
Copyright © University of the People 2020. All rights reserved.

    
Reset user tour on this page

You might also like