Fanny
Fanny

Reputation: 151

Python 3 Raising and catching exceptions

How can I try something in one function and then pass the except handling process to another function?

I want to be able to try 2 functions and if both of them returns an error both errors will be handeld. but if one of them work then everything should be fine and no error message should be returned (the function that works should be returned). Even if one of the function I tried in the try block crashed.

maybe there is a link that describes this typ of error handling?

Upvotes: 1

Views: 53

Answers (2)

Brian
Brian

Reputation: 1998

A nested try/except block should get that done:

try:
    function1()
except:
    try:
        function2 ()
    except:
        # Do something...

The first function runs, then if an exception occurs, the second funcrion runs. If both fail, they're handled in the final except block.

As for the second question, you can just raise the error directly when reading the file, then the __init__ except block can handle it.

Upvotes: 2

Lolgast
Lolgast

Reputation: 339

I'm not sure if I understand you correctly, but perhaps this will help:

def f1():
    raise ValueError

def f2():
    return "Success!"

def f():
    result = None
    try:
        result = f1()
    except:
        pass

    try:
        result = f2()
    except:
        pass

    if result is not None:
        return result
    else:
        print "Both function crashed!

I hope this answers your question, or if not, explain what other functionality you want.

Upvotes: 0

Related Questions