rjayy
rjayy

Reputation: 13

Try Except handling with a function in Python

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.

Upvotes: 1

Views: 717

Answers (4)

barker
barker

Reputation: 1055

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")

Upvotes: 0

GOVIND DIXIT
GOVIND DIXIT

Reputation: 1828

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

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

Upvotes: 0

Zachary Oldham
Zachary Oldham

Reputation: 868

It will fall through to your try-except clause.

Upvotes: 0

Jmonsky
Jmonsky

Reputation: 1519

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

Upvotes: 3

Related Questions