In the lesson, we are taught that “try” and “except” statements are used to check for possible errors a user might encounter. However, I suppose that the process of checking errors does not fulfill the final scope of any control flow, but it is just used complementary in order to write a clean code without errors.
If this right, I would expect that “try” and “except” statements would be used in conjuction with other statements such as “if, else” etc, all written in the same code/function.
So, my question is , which is the right order to combine all these statements when writing the parts of a function? Could you please give an example?
the vital piece of information missing here is that we can also throw exceptions:
def validate_username(username):
if ( len(username) < 5 ):
raise Exception("Username to short")
def main():
username = raw_input("input username: ") # replace with input if you use python3
try:
validate_username(username)
except Exception as e:
print(e)
main()
this also explains what happens when exceptions occur.
you could expand the validate_username() function with a lot more exceptions, so then the control flow logic (if, elif, else) is within the validate_username, then other people can use your function handle the exception as they like.
def raises_value_error():
raise ValueError
try:
raises_value_error()
except ValueError:
print(“You raised a ValueError!”)
Do we need indent "try"and “except”? If they are statements like “if” in a function, why is the indention different ?
try and except have the same nesting rules? When you want a try/except statement within an if statement you get:
if some_condition:
try:
# some code
except SomeException:
# something to do when the exception occured
I do not see any result on console for my code. Please help me to know where I made a mistake.
Your indention/nesting is off. print(shipping_cost_drone(1.5))
is nested in the body of the function itself, and unreachable after a return statement, just to name one thing.
Okay, so can we use if-else control flow inside a try statement to check for different errors? I know it may be a lengthier process and a longer code, but just out of curiosity…
I am referring to the process of checking multiple errors as illustrated by @jephos249 on this page:
you could, but the recommend way would be what appylpye does:
# Slice the pizza!
pizza_mass = 320.0 # 320.0 grams
while True:
try:
num_slices = int(input("Serve the pizza as how many slices? "))
slice_mass = pizza_mass / num_slices
except ValueError: # Input cannot be interpreted as an int.
print("Enter an integer, please.")
continue
except ZeroDivisionError: # Input was 0.
print("Cannot serve it as zero slices.")
continue
if num_slices < 0: # Input was negative.
print("Cannot serve a negative number of slices.")
continue
break
print("The mass of each pizza slice is {:0.2f} grams.".format(slice_mass))
to use multiple except clauses.
Great! That helped a lot… Thank you Sir !!!
In the try can i use more than one variable like
try:
nikola_tesla, richard_p_feyman
except (valueError, SyntaxError,…)
print(“I don’t know”)
The try
block can contain the code we would normally use as if there were no errors expected. The variables are not a factor. It’s just code that may raise an exception, hence the try
block and its attendant except
to handle the exceptions.
Understood my professor. Thank you.