Skip to content

Instantly share code, notes, and snippets.

@elowy01
Last active January 18, 2023 09:15
Show Gist options
  • Save elowy01/88b17e4d48fea786bdda4278418c7dc4 to your computer and use it in GitHub Desktop.
Save elowy01/88b17e4d48fea786bdda4278418c7dc4 to your computer and use it in GitHub Desktop.
import math
try:
print(math.sqrt(-9))
except ValueError:
print("inf")
else:
print("fine")
finally:
print("the end")
A:
inf
the end
# Incorrect number of arguments handling
# With sys.exit(1) we cause the script to
# exit
try:
name = sys.argv[1]
except IndexError:
print("Error: please provide a name and a repeat count to the script.")
sys.exit(1)
# Handling 2 types of exceptions. IndexError is raised because incorrect
# number of args. ValueError is raised because of arg not being integer
try:
repeat_count = int(sys.argv[2])
except IndexError:
print("Error: please provide a name and a repeat count to the script.")
sys.exit(1)
except ValueError:
print("Error: the repeat count needs to be a number.")
sys.exit(1)
# Handling errors when writing into a file.
# Because it can throw different exceptionsm when need the
# code being capable of dealing with the different types
# 'else' block will contain the code to be executed if not errors
# thrown
try:
f = open("root_files/name_repeated.txt", "w")
except (OSError, IOError) as err:
print("Error: unable to write file (", err, ")")
for i in range(1, repeat_count + 1):
print(i, "-", name)
else:
names = [name + "\n" for i in range(1, repeat_count + 1)]
f.writelines(names)
f.close()
# This exception has to do when a certain key in a dict does not exist
# ages.py
ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}
person = input('Get age for: ')
try:
print(f'{person} is {ages[person]} years old.')
except KeyError:
print(f"{person}'s age is unknown.")
#using_try.py
import sys
import random
try:
print(f"First argument {sys.argv[1]}")
args = sys.argv
random.shuffle(args)
print(f"Random argument {args[0]}")
except (IndexError, KeyError) as err:
print(f"Error: no arguments, please provide at least one argument ({err})")
except NameError:
print(f"Error: random module not loaded")
else:
print("Else is running")
finally:
print("Finally is running")
"""
We did import random so that it is possible to successfully run the script. Let's give this a run to see how it goes:
$ python3.7 using_try.py
Error: no arguments, please provide at least one argument (list index out of range)
Finally is running
$ python3.7 using_try.py testing
First argument testing
Random argument using_try.py
Else is running
Finally is running
$
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment