1

I'm not very well versed in exception handling, and was wondering what happens in a case where the try successfully calls a function, but then there is an error within said function.

try:
    foo()
except:
    ...

def foo():
    ...    # error happens here (no exception handling)

Is the error handled or will we get an error in this case.

4
  • For above case, error will be caught from try and the system will run the content inside except Commented Jul 16, 2019 at 19:40
  • I googled "python exception tutorial" and the very first result covers this (and more!) :) realpython.com/python-exceptions Commented Jul 16, 2019 at 19:42
  • I have added an answer hope it will help you Commented Jul 16, 2019 at 19:45
  • Design a little test script (by generating an exception in foo and putting a print statement in the except clause)! You'll go farther faster if you don't rely on others to hand you answers that you can discover for yourself. Commented Jul 16, 2019 at 19:53

4 Answers 4

3

The error would be caught by the try outside of the function.

Sign up to request clarification or add additional context in comments.

Comments

0

It will fall through to your try-except clause.

Comments

0

Try this to catch your error, whenever the specific error occurred the except block code will run:

try:
    foo()
except ErrorName:
   # handle ErrorName exception

Comments

0

Just to clarify what's going on:

This program fails due to the function being called before defined:

try:
    foo()
except:
    print("failed")
def foo():
    print("my string")  

The error is caught in the try, thus printing "failed"

Defining the function prior makes the program work:

def foo():
    print("my string")
try:
    foo()
except:
    print("failed")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.