0% found this document useful (0 votes)
232 views29 pages

CS 1101 - AY2022-T2 - Discussion Unit 8

Programming 1

Uploaded by

Lect urer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
232 views29 pages

CS 1101 - AY2022-T2 - Discussion Unit 8

Programming 1

Uploaded by

Lect urer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

CS 1101 Programming Fundamentals - AY2022-T2


Dashboard / My courses /
CS 1101 - AY2022-T2 / 30 December - 5 January /
Discussion Forum Unit 8 /
Discussion Unit 8

 Search forums

Discussion Forum Unit 8


Discussion Unit 8

Settings

Display replies in nested form

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

Discussion Unit 8
by Leonidas Papoulakis (Instructor) - Wednesday, 10 November 2021, 7:12 AM

Describe how catching exceptions can help with file errors. Write three Python examples that actually generate file 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 Unit 8


by Ahmet Yilmazlar - Thursday, 30 December 2021, 11:30 AM

1. Describe how catching exceptions can help with file errors

Catching exceptions that uses the try: statements can be used to resolve file errors. This is achieved by checking each part of
our file when our code is been ran. When the part of the file that is been run is error free, the code will keep on running. But if
an error is found, we can use the second part of the try: statement to identify the error and fix it in other to stop the program
from crashing 

2. Write three Python examples that actually generate file errors on your computer and catch the errors with try:
except: blocks. Include the code and output for each example in your post. 

Example 1 
Because we can’t add the string int; the try statement will go directly to except

İnput:

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 1/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

try:
  print('Hello'+987)
except:
  print(''error 1'')

Output
== RESTART: C:/Users/user/AppData/Local/Programs/Python/Python39/test code.py ==
error 1

Example 2
When we input a number, the code will run smoothly while, if we change the number to a character, it will immediately go to
except.

İnput:
try:   
  v = int(input("enter a number: "))
except:    
   print("error 2")

Output:
== RESTART: C:/Users/user/AppData/Local/Programs/Python/Python39/test code.py==
enter a number: 1
>>> 
== RESTART: C:/Users/user/AppData/Local/Programs/Python/Python39/test code.py==
enter a number: @
error 2

Example 3
By not declaring (j), an error will be presented, while the error will be printed by the try statement.

İnput
try:
 print(j)
except NameError:
  print(''Error 3'')
Output
== RESTART: C:/Users/user/AppData/Local/Programs/Python/Python39/test code.py
==
Error 3

3. 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 an actual Python code.

If I am  faced with a large production program, I will look deep into each section and reduce the amount of code inside
thestatement until I locate the exact part of the code that is not working. It is also important to include specific exceptions that
will help recovering and handling errors that might arise when using the program, such as: except TypeError and ValueError.

343 words

Permalink Show parent

Re: Discussion Unit 8


by Luke Henderson - Monday, 3 January 2022, 2:22 AM


The brief appears to ask for examples of "file errors" rather than standard python errors as you have demonstrated. Based
on the reading material for this week it would appear to be asking for file read or write errors and how can we avoid them.
Nonetheless you have demonstrated an understanding of the try: except: structure
56 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 2/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Permalink Show parent

Re: Discussion Unit 8


by Samrawi Berhe - Tuesday, 4 January 2022, 4:51 AM

Dear Ahmet, it a nice example you provided regarding exception handling. But it would be better if you had understood
the assignment and answered based on that. Because we were supposed to answer for file-related exception catching.
37 words

Permalink Show parent

Re: Discussion Unit 8


by Fouad Tarabay - Tuesday, 4 January 2022, 5:44 AM

Hello ahmet, you did a great work in explaining how exception handling helps but the examples must be on files.
20 words

Permalink Show parent

Re: Discussion Unit 8


by Samrawi Berhe - Saturday, 1 January 2022, 1:55 PM

Discussion Forum Unit 8

Describe
how catching
exceptions can
help with file
errors.
Write three Python examples that actually generate file errors on
your computer
and catch the errors with try: except:

Answer

"A lot of things can go wrong when you try to read and write files. If you try to open a file

that doesn’t exist, you get an IOError" (Downey, 2015). This shows that there is a bad result if we do not handle the exception
before it is caused. This is because we write a program to solve problems and the end-user may not know how it is doing
things. So, he can not understand what it is saying. Therefore, we have to catch the exception and write something the user
can understand.  This is called exception handling. This can be done using try: ............ except/ finally block. So, examples are
below.

The program below searches through the directory and


displays the result to the screen. The script looks as follows.

The output is below



Traceback (most recent call last):

File
"F:\Programing
I\CS1010\Chapter4\Written_Assignment\os_manupilation.py", line 13, in
<module>

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 3/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

   search_dir('D:')

File
"F:\Programing
I\CS1010\Chapter4\Written_Assignment\os_manupilation.py", line 5, in
search_dir

   for name in
os.listdir(dir_name):

PermissionError: [WinError 21] The device is not ready: 'D:'

Process finished with exit code 1

From the above output, we see that the interpreter rases


permission error and adding the device is not ready. So, to solve this I
should
have to check first if the directory is available or not. If the directory is not
available, should catch the exception before
it got caught by the interpreter,
and check the current directory then change to it. So, let us fix it and see
the result.

After fixing the previous error, the script looks as


follows.

So, the output is as follows.

Path not found

Process finished with exit code 0

Let us see when the directory exists. Let us change the


directory to F.

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 4/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

As we can see from the above, the interpreter


throws NotADirectoryError. This is because we do not tell what to do with files
we are only told with directories and
the interpreter does not know what to do if it gets files in the folders. So,
we should
manage this error.
The script after fixing the errors is as follows.

And the output of the above code looks as follows.

C:\Users\PC\AppData\Local\Programs\Python\Python310\python.exe
"F:/Programing
I/CS1010/Chapter4/Written_Assignment/os_manupilation.py"

The folder name F:.idea  is found

F:5 test cases output.rtf is not a folder

F:abab.py is not a folder

F:absolute.py is not a folder

F:all_codes.py is not a folder

F:bool.py is not a folder

The folder name F:code.PNG 


is found

The folder name F:create_file.py  is found

F:divmod.py is not a folder

F:enamurate_function.py is not a folder

F:fileopen.py is not a folder

The folder name F:file_bject.py  is found

The folder name F:file_open_error.py  is found



F:file_write_error.py is not a folder

F:histogram.py is not a folder

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 5/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

F:histo_gram.py is not a folder

F:hypotenuse.py is not a folder

F:inpt_file is not a folder

F:invresed.py is not a folder

F:is_lower_case.py is not a folder

F:is_lower_case2.py is not a folder

F:is_lower_case3.py is not a folder

F:is_lower_case4.py is not a folder

The folder name F:is_lower_case5.py  is found

The folder name F:is_power.py  is found

The folder name F:item_method.py  is found

F:learning_journal_U7_Dictionary.py is not a folder

F:make_dir.py is not a folder

F:match.py is not a folder

Let see another example of an exception that I want to the program


that reads a file and displays the content to the console.
So, the script is as
below.

The output of the above code is as follow:

From the above output, we can see that the interpreter throws
a file not found an exception. So, let us handle this error using
try: except. The script
is as follows. 

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 6/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

And the output is now as below.

                                     Reference
Downey, A. (2015). Think Python: How to think like a computer scientist.

637 words
Tags:
Discussion Forum Unit 8

Permalink Show parent

Re: Discussion Unit 8


by Luke Henderson - Monday, 3 January 2022, 2:25 AM

Excellent post with a diverse group of file errors to demonstrate your understanding of this weeks subject material. It is
clear you are very familiar with python and your level seems to be more advanced than this course. You always do a great
job of explaining and provide good examples. great job
52 words

Permalink Show parent

Re: Discussion Unit 8


by Samrawi Berhe - Tuesday, 4 January 2022, 4:30 AM

Thank you, Luke, for your comments.


6 words

Permalink Show parent

Re: Discussion Unit 8


by Ahmet Yilmazlar - Monday, 3 January 2022, 10:21 AM

great work easy to understand


5 words

Permalink Show parent


Re: Discussion Unit 8


by Samrawi Berhe - Tuesday, 4 January 2022, 4:31 AM

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 7/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Thank you, Ahmet, for your comments.


6 words

Permalink Show parent

Re: Discussion Unit 8


by Wilmer Portillo - Monday, 3 January 2022, 6:02 PM

Great examples with different errors. Thank you very much!


9 words

Permalink Show parent

Re: Discussion Unit 8


by Samrawi Berhe - Tuesday, 4 January 2022, 4:32 AM

Thank you, Wilmer, for your comments.


6 words

Permalink Show parent

Re: Discussion Unit 8


by Fouad Tarabay - Tuesday, 4 January 2022, 5:47 AM

Hello Samrawi, as always you did a great job in explaining and giving the right examples clearly. Well done!
19 words

Permalink Show parent

Re: Discussion Unit 8


by Simon Njoroge - Tuesday, 4 January 2022, 11:44 PM

Your explanation and input is very clear. It makes our work to understand the topic even easier. You have clearly explained.
Thank you for your input.
26 words

Permalink Show parent

Re: Discussion Unit 8


by Janelle Bianca Cadawas Marcos - Wednesday, 5 January 2022, 9:38 AM

Excellent post as always. Easy to understand and easy to read. Great work.
13 words

Permalink Show parent

Re: Discussion Unit 8


by Stephen Chuks - Wednesday, 5 January 2022, 2:19 PM

Great one from you. Following your post will help others that doesn't understand the assignment have a better grasp
of it.
Keep it up
24 words

Permalink Show parent

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 8/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Re: Discussion Unit 8


by Juan Duran Solorzano - Wednesday, 5 January 2022, 7:41 PM

Dear Samrawi,

Excellent answer, it helped me to fully understand this week's topic.

Kind regards
15 words

Permalink Show parent

Re: Discussion Unit 8


by Peter Odetola - Wednesday, 5 January 2022, 9:10 PM

A good, work well done Samrawi. Keep it up.


9 words

Permalink Show parent

Re: Discussion Unit 8


by Fouad Tarabay - Sunday, 2 January 2022, 4:36 PM

First we have IOError which throws an error if the file we want to read doesn't exist.

Example:

code:

try:

f = open('fouad.txt','r')

except IOError:

print("The file doesn't Exist")

output:

The file doesn't Exist

Here in the above code I tried to read a file that doesn't exist which will throws an error since the 'r' format doesn't create a file
it only read from the existing files.

Second we have PermissionError which throws an error if we want to read or write to a file we don't have the permission to
access.

Example:

code:

try:

f = open('fouad','w')

except PermissionError:

print("You Don't have access to this file")

output:

You Don't have access to this file


In the above code I tried to write to a file that I don't have access to so the try catch block detect it with PermissionError.

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 9/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Third Error which is the IsADirectoryError, that throws an error is we are trying to open a directory to read from.

Example:

code:

import os

cwd = os.getcwd()

try:

f = open(cwd)

except IsADirectoryError:

print("This is a directory")

output:

This is a directory

Since os.getcwd() returns the current directory the try except block throws an error since we cannot open a directory to read
from.

In building large programs while writing a code to open a file I would put each time I open a file in a try except block and
writing the suitable printing method to make it more obvious to what error I am dealing with so I can fix it.
256 words

Permalink Show parent

Re: Discussion Unit 8


by Luke Henderson - Monday, 3 January 2022, 2:17 AM

Concise coverage of 3 different file errors and how to avoid them. The post is a little short and you could have gone into
more depth with your answer to the last question.
33 words

Permalink Show parent

Re: Discussion Unit 8


by Ahmet Yilmazlar - Monday, 3 January 2022, 10:22 AM

nice work
2 words

Permalink Show parent

Re: Discussion Unit 8


by Wilmer Portillo - Monday, 3 January 2022, 6:03 PM

On point. Great work!


4 words

Permalink Show parent

Re: Discussion Unit 8


by Samrawi Berhe - Tuesday, 4 January 2022, 4:41 AM


Dear Fouad, fantastic explanation. You have made a great job with clear and precise examples. I have learned something
different which I did not know before that is "IsADirectoryError" to check whether it is a directory or not. Thank you!
40 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 10/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Permalink Show parent

Re: Discussion Unit 8


by Janelle Bianca Cadawas Marcos - Wednesday, 5 January 2022, 9:40 AM

Good work on your code. However, next time fix the spacing. The spacing disappears sometimes when you copy+paste, it
makes it hard to read if you don't fix it here. It would be nice to have a bit more on the explanations.
42 words

Permalink Show parent

Re: Discussion Unit 8


by Peter Odetola - Wednesday, 5 January 2022, 9:12 PM

Hello Fouad, Thanks for the excellent effort put forth to clarity of the work.
14 words

Permalink Show parent

Re: Discussion Unit 8


by Yahya Al Hussain - Wednesday, 5 January 2022, 11:43 PM

great work
2 words

Permalink Show parent

Re: Discussion Unit 8


by Luke Henderson - Monday, 3 January 2022, 1:35 AM

the try: except: structure in python is a great way to have your program still run even if there is an issue such as a file not
found, permission issues or the file is misspelled. You may want to have your code run on someone else's computer and their
directory structure or files are likely not the same as yours. Even if the program cannot run as intended this structure allows us
to raise an error which can give the user some idea of what is wrong.

Here are 3 example programs which demonstrate the usefulness of this structure.

if the required file does not exist we can notify the user so they can put that file in the correct directory.

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 11/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

In my second example I intentionally remove write permissions for the file I wish to access, to demonstrate the fact that if my
program is running on someone else's computer there is the potential that the file the program needs to access may for some
reason or other be set to read only permission.

Now I attempt to write some data to that file.

I can get around this issue and notify the user of the problem with a well thought out error message.

Lastly there may be an issue that the volume that the user is trying to run the program on is a read only file system.



Again we can get past this with try: except: and inform the user of the issue so they can try running the program on a file

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 12/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

system they have access too.

There are many things to consider when designing software that others will use. Portability is one key factor. We want to make
sure our code will run on as many platforms as possible without error. Designing a program which checks which OS the user is
running and altering the flow of the program based on that can help a great deal. If the program is designed to open and edit
.txt files and it doesn't matter what the file is called, we can use os.listdir() function along with string methods to check whether
there is .txt in the file name.

361 words

Permalink Show parent

Re: Discussion Unit 8


by Ahmet Yilmazlar - Monday, 3 January 2022, 10:21 AM

great work
2 words

Permalink Show parent

Re: Discussion Unit 8


by Wilmer Portillo - Monday, 3 January 2022, 6:04 PM

The notes were great in understanding the examples. Keep it up.


11 words

Permalink Show parent

Re: Discussion Unit 8


by Samrawi Berhe - Tuesday, 4 January 2022, 4:47 AM

Dear Luke, it is a great job, wow. Your explanation and the example you provided are on point. I am able to learn another
way of handling exceptions. You also well-understood what a software designing should be.
37 words

Permalink Show parent

Re: Discussion Unit 8


by Fouad Tarabay - Tuesday, 4 January 2022, 5:50 AM

Hello Luke, You did a great job in your explanation and your discussion covers every detail that must be discussed. Thank
you and keep it up!
26 words

Permalink Show parent


Re: Discussion Unit 8


by Simon Njoroge - Tuesday, 4 January 2022, 11:45 PM

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 13/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

You have done a good job in solving this problem. You have clearly made a positive input in this discussion. Well done and
keep it up.
26 words

Permalink Show parent

Re: Discussion Unit 8


by Stephen Chuks - Wednesday, 5 January 2022, 2:17 PM

Good examples and comprehensive for easy understanding


7 words

Permalink Show parent

Re: Discussion Unit 8


by Peter Odetola - Wednesday, 5 January 2022, 9:14 PM

Hi Luke, Your work is well detailed and it shows your in-depth understand. Thanks for the contribution to make me learn
better with your input
25 words

Permalink Show parent

Re: Discussion Unit 8


by Yahya Al Hussain - Wednesday, 5 January 2022, 11:43 PM

simple to read, and detailed


5 words

Permalink Show parent

Re: Discussion Unit 8


by Wilmer Portillo - Monday, 3 January 2022, 5:36 PM

Discussion Assignment Unit 8:

Describe how catching exceptions can help with file errors.


‘Catching exceptions’ is very essential for programmers as it is very useful in resolving raised issues at runtime instead of
wantonly closing a program. In simple terms, this feature literally catches possible issues at runtime.

Write three Python examples that actually generate file errors on your computer and catch the errors with try: except: blocks.
Include the code and output for each example in your post. 
Example 1:
Input:

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 14/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Output:

Debug: exception happen=[Errno 2] No such file or directory: ‘exampel.txt’


Example 2:

Input:

Output:


Debug: exception happen= write() argument must be str, not int

Example 3:
https://my.uopeople.edu/mod/forum/discuss.php?d=640912 15/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8
Input:

Output:

References:

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

146 words

Permalink Show parent

Re: Discussion Unit 8


by Simon Njoroge - Tuesday, 4 January 2022, 11:46 PM

Your use of function to except errors is clear that is working. You have also explained clearly how to solve the problems.
Your input has been positive . Keep it up.
31 words

Permalink Show parent

Re: Discussion Unit 8 


by Janelle Bianca Cadawas Marcos - Wednesday, 5 January 2022, 9:42 AM

Good work on your code. However, you left out one part of the prompt. You forgot to answer "Describe how you might

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 16/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

deal with each error if you were writing a large production program. These descriptions should be general ideas in English,
not actual Python code." Also it would be nice if you added more sentences into your discussion post. As well as
comments in your code.
67 words

Permalink Show parent

Re: Discussion Unit 8


by Crystal Noralez - Monday, 3 January 2022, 7:32 PM

Discussion Forum Unit 8

Describe how catching exceptions can help with file errors. Write three Python examples that actually generate file 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.

Example 1

try:

a = 10/1

print(a)

except:

OneDivisionError

print("One!")

Interpreter output

: D:\Users\Crystal Noralez\Documents\sync\UoPeople\Term 3\Programming Fundamentals\Unit 8\Assessments\Discussion


Forum Unit 8.py

One!

Example 2

try:

Nor = 28

nor = nor + ' 1 '


except:

TypeError

print('Wrong type')

Interpreter output

: D:\Users\Crystal Noralez\Documents\sync\UoPeople\Term 3\Programming Fundamentals\Unit 8\Assessments\Discussion


Forum Unit 8.py

Wrong type

Example 3

try:

nor = []

print(nor[1])

except:

IndexError

print("Index error")

Interpreter output

: D:\Users\Crystal Noralez\Documents\sync\UoPeople\Term 3\Programming Fundamentals\Unit 8\Assessments\Discussion
Forum Unit 8.py

Index error

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 17/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Reference

Downey, A. (2015). Think Python| How to Think Like a Computer Scientist: Vol. Version 2.2.23 (2nd Edition). Green Tea Press.
https://my.uopeople.edu/pluginfile.php/1404469/mod_page/content/3/TEXT%20-%20Think%20Python%202e.pdf
170 words

Permalink Show parent

Re: Discussion Unit 8


by Stephen Chuks - Wednesday, 5 January 2022, 2:16 PM

Nice examples
2 words

Permalink Show parent

Re: Discussion Unit 8


by Crystal Noralez - Wednesday, 5 January 2022, 8:50 PM

Thanks.
1 words

Permalink Show parent

Re: Discussion Unit 8


by Simon Njoroge - Tuesday, 4 January 2022, 5:04 PM

Catching exception helps in file errors. Ordinarily in python if you generate an error the program always gives an error
message that suggest what type of an error has been generated. One can deal with such errors by creating exception options .
Compiler errors such as syntax errors causes the program to return an error message. Such error messages are accompanied
by definition of the type of error one made or the system comes across with. Run time errors may be generated by the
program user and so one has to create exceptions for such errors in the process of generating the system. Below are 3
examples of the errors and their solutions or exception options.  

Script of the 3 examples

https://my.uopeople.edu/pluginfile.php/1521295/mod_forum/post/15459474/discussion%20script.py

Example 1 - Exception of division by 0 

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 18/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Example 2 - Type of data entry error 

Example 3 - Wrong key in dictionary exception 


The easiest way to deal with the errors is by using except option in the program. This would really assist the users of the
program especially large programs to be able to identify the cause of the errors generated by the programs. This would further
guide the user on actions to take in order to have the correct feedback. 

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 19/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

205 words

Permalink Show parent

Re: Discussion Unit 8


by Juan Duran Solorzano - Wednesday, 5 January 2022, 7:50 PM

Dear Simon,

Great examples on how to use try and except statements, therefore the topic given was to explain the statements when we
deal with files. open(), read() etc...

Keep it up

Regards
33 words

Permalink Show parent

Re: Discussion Unit 8


by Crystal Noralez - Wednesday, 5 January 2022, 8:51 PM

Hi Simon,

Very great example. Keep up the good job.


10 words

Permalink Show parent

Re: Discussion Unit 8


by Yahya Al Hussain - Wednesday, 5 January 2022, 11:44 PM

each time your subsumptions get better , keep up the great work !
13 words

Permalink Show parent

Re: Discussion Unit 8


by Janelle Bianca Cadawas Marcos - Wednesday, 5 January 2022, 9:23 AM

Catching exceptions can help with file errors since we can program
our code to tell us what exactly the error is if we know what
to do
to cause an error.

Input:

#making a text file for the examples

text = open('hello.txt','w')

text.write('Hello\n') 
text.write('Good day\n')

text.close()

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 20/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Output:

<built-in method close of _io.TextIOWrapper object at


0x000001DBA867E330>

Input 1:

#file not found error

def print_file(s):

try:

ftxt = open(s) #open given file

for line in ftxt: #prints each line of file

word = line.strip()

print(word)

except:

print('File not found.')

print('With non-existing file:')

print_file('notext.txt') #call out function with a file that does not


exist

print('With existing file:')

print_file('hello.txt') #call out function with file that exists

Output 1:

With non-existing file:

File not found.

With existing file:

Hello

Good day

I can deal with this error by editing the code so if the file is not
found, it will create a new text file instead of just looking for a
nonexistent file.

Input 2:

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 21/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

import os

#file directory/file already exists error

def new_dir(s):

try:

os.mkdir('./%s' %s) #make directory

print('./%s made successfully' %s)

except:

print('File/Directory already exists.')

print('With existing file/directory:')

new_file('hello.txt') #call out function with file that exists

print('With non-existing file/directory:')

new_file('folder') #call out function with a file that does not exist

Output 2:

With existing file/directory:

File/Directory already exists.

With non-existing file/directory:

./notext made successfully

I can deal with this error by changing it so that it will open the
directory instead if it already exists instead of making a new
one.

Input 3:

#cannot only open files error

def write_in(s,t):

try:

ftxt = open(s,'w') #opens file in write mode

ftxt.write(t)

ftxt.close()

print('Successfully wrote %s in %s.' %(t,s))



except:

print('Error: %s is not a file.' % s)

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 22/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

print('Using a non-file:')

write_in('folder','textdoc')

print('Using a file:')

write_in('hello.txt','Hey')

Output 3:

Using a non-file:

Error: folder is not a file.

Using a file:

Successfully wrote Hey in hello.txt.

I can deal with this error by making it so that it creates it as a


file if it’s only a file directory.

335 words

Permalink Show parent

Re: Discussion Unit 8


by Juan Duran Solorzano - Wednesday, 5 January 2022, 7:45 PM

Dear Janelle,

you showed a great understanding of the task given for this week. I like your examples as they helped me to understand
more about this week's topic.

Regards
30 words

Permalink Show parent

Re: Discussion Unit 8


by Crystal Noralez - Wednesday, 5 January 2022, 8:52 PM

Hi Janelle,

Exceptional work well done! You managed to solve the given problem in detail and accurately.
17 words

Permalink Show parent

Re: Discussion Unit 8


by Stephen Chuks - Wednesday, 5 January 2022, 11:03 AM 

#The 3 python error-exception examples I want to give are the value error,

# the zero division error and the file note found

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 23/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

a=10

b=0

c=a/b

#this gave a ZeroDivisionError: division by zero error. but introducing the

#try and except block controlled this error and give additional information about the message

try:

a = 10

b = 0

c = a / b

except ZeroDivisionError:

print('Error, you can not divide a number by zero')

output: Error, you can not divide a number by zero.

#value error

import math

num=-10

print(f"Square Root of {num} is {math.sqrt(num)}")

#This gave ValueError: math domain error. but using the try and except block, the
#error message was controlled and more information was given

try:

print(f"Square Root of {num} is {math.sqrt(num)}")

except ValueError:

print("Enter a positive number")

Output: Enter a positive number

#file not found error. Trying to open a file that does not exist.

with open ('file.txt', 'r') as a:

contents=a.read

print(contents)

#running this file gave FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

#But with the try and except block, I provided more information on the error

try:

with open ('file.txt', 'r') as a:

contents=a.read

print(contents)

except FileNotFoundError:

print('File does not exist, please check that the file is in the present directory or correct path was given')

Output: File does not exist, please check that the file is in the present directory or correct path was given

Errors and bugs cannot be completely eliminated from any computer program, especially when working on a large production
program. In such, a good way to deal with errors is through good development and design. Incorporating incremental
development is a good way to reduce the chances of errors occurring in your program.
285 words

Permalink Show parent

Re: Discussion Unit 8


by Crystal Noralez - Wednesday, 5 January 2022, 8:53 PM

Dear Chuks,

You did a vey excellent job on the explanation. Keep up the great job.
16 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 24/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

Permalink Show parent

Re: Discussion Unit 8


by Juan Duran Solorzano - Wednesday, 5 January 2022, 7:26 PM

Describe how catching exceptions can help with file errors.

Using a try statement can help us to check if the part of the code runs smoothly with no errors, in case the code has some
mistakes we could use except statement to catch the error and give the chance to fix it without crashing the program. It is very
similar that if and else.

Catching exceptions is a way to handle errors in a program that you don't know about at the time of coding the program.

The statements mentioned also can be very useful to help us when we work with files, we could add a block to try to manage
files and if the path and code are correct the program will run with no problems, otherwise, the exception will be called and
will catch the error. 

Write three Python examples that actually generate file errors on your computer and catch the errors with try: except blocks.

Include the code and output for each example in your post.

# example 1 using try and except

try:

  # This will cause an error because the variables a and b are not defined

  print(a + b)

except:

  print("There was an error, the variables are not defined")

#Output:

"There was an error, the variables are not defined"

# example 2 using try and except with files

# This example will open a file and print the contents of the file, if there is an error it will print the error,
but the program will not stop running and the file will be closed

try:

  # Try to open the file in read mode but the path is not correct

  f = open("text", "r")

  print(f.read())  # read the contents of the file and print them

  f.close()  # close the file

except:

  print("There was an error, the file was not found")

# Output:

# There was an error, the file was not found

# example 3 using try and except with files

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 25/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8
# This example help us to write on files and print the contents of the file,

try:

  # Try to open the file in write mode but the path is not correct

  f = open("text.txt", "r")  # open the file in read mode

  # write on the file, this part will make the program crash because the file was open ONLY in reading mode.

  f.write("This is a grocery list:")

  f.close()  # close the file

  # Try to open the file in read mode but the path is not correct

  f = open("text.txt", "r")

  print(f.read())  # read the contents of the file and print them

  f.close()

except:

  print("There was an error when trying to write on the file")

446 words

Permalink Show parent

Re: Discussion Unit 8


by Peter Odetola - Wednesday, 5 January 2022, 8:18 PM

CS1101 DISCUSSION FORUM UNIT 8

1. Describe how catching exceptions can help with file errors

2. Write three Python examples that actually generate file errors on your computer and catch the errors with try: except: blocks.
Include the code and output for each example in your post.

3. 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.

QUESTION #1

Catching exceptions help us with file errors. It will try to run a part of our code so as to be able to check the other part of our
file. If the part we are testing does not have an error, the code will keep running. If an error is found, we can easily verify it with
the second part of the try statement “except”, which will help us identify the particular error. This is how we can fix the error
without the program ending up in a crash.

QUESTION #2

# Example 1: Error of adding a string to int. The try statement will go immediately to except.

+ Code:

try:

print("Jackson" + 429)

except:

print("error 1")

+ Output:

==================== RESTART: D:\Users\lpak\Desktop\test.py =================

error 1

>>> # Example 2: Error of inputting a character when an int is originally declared. If we try to input a number, the code will run
normally, but if we put a character, it will go immediately to the except:

+ Code:

try:

x = int(input("enter a number: "))

except:


print("error 2")

+ Outputs:

==================== RESTART: D:\Users\lpak\Desktop\test.py =================

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 26/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

enter a number: 24

>>> ==================== RESTART: D:\Users\lpak\Desktop\test.py =================

error 2

>>> # Example 3: Error of not declaring a variable. The try statement will print the error:

+ Code:

try:

print(z)

except NameError

print("error 3")

+ Output:

==================== RESTART: D:\Users\lpak\Desktop\test.py =================

error 3

>>>

QUESTION #3

In writing a large production program, I will reduce the number of code inside the try statement until I find the exact part of
the code that is not working. I will also include specific exception that will recover and handle such error that could happen
during the use of the program like except TypeError - ValueError.

Reference:

Python Exception Handling Using try, except and finally statement. (n.d). Programiz. https://www.programiz.com/python-
programming/exception -handling
380 words

Permalink Show parent

Re: Discussion Unit 8


by Yahya Al Hussain - Wednesday, 5 January 2022, 11:36 PM

catching exceptions can help with file errors by showing us what went wrong  without stopping the program from
running.

example 1. 404 Error

raised when a page is requested but is not avalable.

Example

try:

  path = 'myWebsite.com/offer'

  with open(path) as f:

      print(f)
except:

  print("404 Not Found");

Example 2. 403 Error

Raised when The user tries to inter invalid data.


Example:

ry:
blue = 600

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 27/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8

blue = blue + ' 6 '


except:
TypeError
print('invalid data type')
Example 3

3. PermissionError
Raised when trying to run an operation without the adequate access rights 
Example
try:

f = open("TopSecret.txt")

try:

   f.write("data")

except:

   print("You are not allowed to access the file")

finally:

   f.close()

except:

print("Something went wrong when opening the file")

119 words

Permalink Show parent

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 the clock at the top of the page.

Due dates/times displayed in activities will vary with your chosen time zone, however you are still bound to the 11:55 PM GMT-5
deadline.

◄ Learning Guide Unit 8

Jump to...

Learning Journal Unit 8 ►

Disclaimer Regarding Use of Course Material  - Terms of Use


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

You are logged in as Stephen Chuks (Log out)


Reset user tour on this page
 www.uopeople.edu










Resources
UoPeople Library 
Orientation Videos
LRC
Syllabus Repository
Honors Lists
https://my.uopeople.edu/mod/forum/discuss.php?d=640912 28/29
1/8/22, 4:17 AM CS 1101 - AY2022-T2: Discussion Unit 8
Honors Lists
Links
About Us
Policies
University Catalog
Support
Student Portal
Faculty
Faculty Portal
CTEL Learning Community
Office 365
Tipalti
Contact us
English (‎en)‎
English (‎en)‎
‫ العربية‬‎(ar)‎

Data retention summary


Get the mobile app

https://my.uopeople.edu/mod/forum/discuss.php?d=640912 29/29

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy