FAQ: Control Flow - Try and Except Statements

This community-built FAQ covers the “Try and Except Statements” exercise from the lesson “Control Flow”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Try and Except Statements

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

2 posts were split to a new topic: Does Try/Except always need to be in a function?

2 posts were split to a new topic: What is an example of try/except?

9 posts were split to a new topic: Should I be looking up unexplained concepts?

def divides(a,b):
try:
result = a / b
print (result)
except ZeroDivisionError:
print (“Can’t divide by zero!”)

Don’t we need to define ZeroDivisionError before “Except”, otherwise how is it going to be operated?

ZeroDivisionError is an exception built into the python programming language.

here is the whole list of built-in exceptions:

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

3 Likes

Hi,

can anyone tell me why this gives me a tick in the checkbox but is different from the solution?

def raises_value_error():
  try:
    raise ValueError
  except ValueError:
    print("You raised a ValueError!")
  
raises_value_error()

An exception should be raised and not be caught

1 Like

What is the usage of the ‘raise’ in try and except statements?
I haven’t learnt about it before and codecademy just brought it here out of blue. I am confused.

6 Likes

raise raises an exception. Raising exceptions can be very useful. In programming its common to encounter new concepts, there is nothing wrong about using google to help you gain information

def raises_value_error():

  raise ValueError
 try:

  raises_value_error()

except ValueError:

  print("You raised a ValueError!")

the above code works but why does the below code does not work because I am raising ValueError1 should work the same way .


 def raises_value_error():
  raise ValueError1
  
try:
  raises_value_error()
except ValueError1:
  print("You raised a ValueError!")

why should it work the same way? ValueError1 is not an existing exception.

Hi

I experimented with the ‘raise’ function and the try / except statements, and am confused by how it works exactly.
If I include an except statement that matches the type of error that my try statement results in, then the except statement is executed (provided my try statement has an error).
But if I want my except statement to raise an error - it will raise both the actual error that the try statement results in, plus the error I have specified after the raise function.
Eg -

try:
  1/0
except:
  raise ValueError

This code above results in both a ZeroDivisionError (because of the try statement error) and the ValueError that I wanted. However, I would expect it only to result in the ValueError.

thankfully not, then you would loose the stacktrace and the error becomes very hard to trace

Currently, your try except only contains one line, but if it where several lines, or even several function calls, loosing the stacktrace would make it very difficult to determine where the error originated.

Ok thanks for the quick reply.
I think I understand.
However I wanted to know why this is the case.

If I code a try and except statement it will execute whatever is under the except statement - it does not mention the error that the try statement results in. So if I include a print function under my except statement, it will print and nothing else.
So if I raise an error under my except statement, why does it also mention the error occurring in the try statement?
Are you suggesting that because the raise function I have included is raising a type of error that does not match the error from the try statement - then both errors are displayed in order to keep the actual error from being hard to trace?

You will need to understand something about the stacktrace:

https://realpython.com/python-traceback/

Normally, when handling an error (with try except) you do this, so your program can continue running. So then you don’t need the stacktrace

but if you then raise an exception, its nice that python is built in such a way, you get the stacktrace.

How come in this exercise, our alternative statement ( the ‘except’ statement) was printed (print("You have made a ValueError)) but in previous examples ( if, else…) the statements weren’t printed, they were just stated?

hey,

I came across mutiple exercises regarding “Try and Except” but it seems like this chapter has been removed from the latest syllabus. Could anyone help explain what happened, and where should I learn this concept now?

1 Like

Same here!

Any admin keen on answering? :slight_smile:

cheers

1 Like