Skip to content

Instantly share code, notes, and snippets.

@misterhtmlcss
Created August 12, 2020 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misterhtmlcss/beb14a2e378e4d3875baf10961a78c59 to your computer and use it in GitHub Desktop.
Save misterhtmlcss/beb14a2e378e4d3875baf10961a78c59 to your computer and use it in GitHub Desktop.
# 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.
# There are two ways to catch an error; handle it gracefully, which is done in the last except statement, but in the first one with ZeroDivisionError we apply the initial part of second implementation that is more dynamic and some would say 'useful' to the user and development team. When an exception is specifically targeted this allows for a software developer to more easily develop an 'antidote' to the issue. In this case division by 0. Possibly this could lead to a solution that upon exception returns 0.
# Describe how catching exceptions can help with file errors.
# Catching errors can mean two things; the graceful handling of your program failing. Rather than a crash! Can anyway anyway 2k bug? This means your code is more durable to errors.
def test_exceptions(num1, num2):
try:
x = num1 / num2
print("\nThe result is", x)
# This is a good exception to include, because this is not an uncommon error. Imagine if every time in school when you used a calculator and divided by zero your calculator had to initialize the program?
except ZeroDivisionError: # (Sharma, 2019)
num2 = input('Give us the number greater than 0 please ')
return test_exceptions(num1, num2)
# This can be an example of the gong show. This nested error handling is a bad pattern. It reduces clarity on the issue, not enhances it and it's difficult to write test code for.
except TypeError:
try:
num2 = input('Please use a number for crying out loud!! ')
return test_exceptions(num1, int(num2))
except ValueError:
num2 = input('dddddPlease use a number for crying out loud!! ')
return test_exceptions(num1, int(num2))
except:
print('\nAll other Errors =======> This error is not pre-defined nor identified, please alert our team team-goofs@facebook.com')
# test_exceptions(1, 0)
# test_exceptions(1, '0')
# test_exceptions(2, 'dd')
# Reference
# Sharma, A. (2019). Exception and Error Handling in Python. Retrieved from https://www.datacamp.com/community/tutorials/exception-handling-pythonDataCamp.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment