Who/How to get the control of the program after an exception has ocurred

how to continue execution after exception in java
how to continue program after exception in java
how to continue execution after exception in c#
try-catch-finally java example
try catch java
how to continue for loop after exception in java
try catch-continue java
does throwing an exception stop execution java

I have always wondered who takes the control of the program after an exception has thrown. I was seeking for a clear answer but did not find any. I have the following functions described, each one executes an API call which involves a network request, therefore I need to handle any possible errors by a try/except and possibly else block (JSON responses must be parsed/decoded as well):

# This function runs first, if this fails, none of the other functions will run. Should return a JSON.
def get_summary():
    pass

# Gets executed after get_summary. Should return a string.
def get_block_hash():
    pass

# Gets executed after get_block_hash. Should return a JSON.
def get_block():
    pass

# Gets executed after get_block. Should return a JSON.
def get_raw_transaction():
    pass

I wish to implement a kind of retry functionality on each function, so if it fails due to a timeout error, connection error, JSON decode error etc., it will keep retrying without compromising the flow of the program:

def get_summary():
    try:
        response = request.get(API_URL_SUMMARY)
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        # Once response has been received, JSON should be 
        # decoded here wrapped in a try/catch/else
        # or outside of this block?
        return response.text

def get_block_hash():
    try:
        response = request.get(API_URL + "...")
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        return response.text

def get_block():
    try:
        response = request.get(API_URL + "...")
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        #
        #
        #
        return response.text

def get_raw_transaction():
    try:
        response = request.get(API_URL + "...")
    except requests.exceptions.RequestException as error:
        logging.warning("...")
        #
    else:
        #
        #
        #
        return response.text

if __name__ == "__main__":
    # summary = get_summary()
    # block_hash = get_block_hash()
    # block = get_block()
    # raw_transaction = get_raw_transaction()
    # ...

I want to keep clean code on the outermost part of it (block after if __name__ == "__main__":), I mean, I don't want to fill it with full of confused try/catch blocks, logging, etc.

I tried to call a function itself when an exception threw on any of those functions but then I read about stack limit and thought it was a bad idea, there should be a better way to handle this.

request already retries by itself N number of times when I call the get method, where N is a constant in the source code, it is 100. But when the number of retries has reached 0 it will throw an error I need to catch.

Where should I decode JSON response? Inside each function and wrapped by another try/catch/else block? or in the main block? How can I recover from an exception and keep trying on the function it failed?

Any advice will be grateful.

You could keep those in an infinite loop (to avoid recursion) and once you get the expected response just return:

def get_summary():
    while True:
        try:
            response = request.get(API_URL_SUMMARY)
        except requests.exceptions.RequestException as error:
            logging.warning("...")
            #
        else:
            # As winklerrr points out, try to return the transformed data as soon 
            # as possible, so you should be decoding JSON response here.
            try:
                json_response = json.loads(response)
            except ValueError as error: # ValueError will catch any error when decoding response
                logging.warning(error)
            else:
                return json_response

This function keeps executing until it receives the expected result (reaches return json_response) otherwise it will be trying again and again.

Tutorial: Exceptions | Java Tutorial, is thrown to the method that called this method. Arnold Schwarzenegger This Speech Broke The Internet AND Most Inspiring Speech- It Changed My Life. - Duration: 14:58. Alpha Leaders Productions Recommended for you

You can do the following

def my_function(iteration_number=1):

    try:
        response = request.get(API_URL_SUMMARY)
    except requests.exceptions.RequestException: 
        if iteration_number < iteration_threshold:
            my_function(iteration_number+1)
        else:
            raise
    except Exception: # for all other exceptions, raise
        raise

    return json.loads(resonse.text)


my_function()

How to continue program execution even after throwing exception , How do you continue a program execution even after throwing an exception? In Java, after an exception is handled, control resumes -----. This is known as the-----model of exception handling. a. after the last catch block (or the finally block, if there is one), termination b. after the last catch block (or the finally block, if there is one), resumption c. just after the throw point, termination

Where should I decode JSON response? Inside each function and wrapped by another try/catch/else block or in the main block?

As a rule thumb: try to transform data as soon as possible into the format you want it to be. It makes the rest of your code easier if you don't have to extract everything again from a response object all the time. So just return the data you need, in the easiest format you need it to be.

In your scenario: You call that API in every function with the same call to requests.get(). Normally all the responses from an API have the same format. So this means, you could write an extra function which does that call for you to the API and directly loads the response into a proper JSON object.

Tip: For working with JSON make use of the standard library with import json

Example:

import json

def call_api(api_sub_path):
    repsonse = requests.get(API_BASE_URL + api_sub_path)
    json_repsonse = json.loads(repsonse.text) 

    # you could verify your result here already, e.g.
    if json_response["result_status"] == "successful":
        return json_response["result"]

    # or maybe throw an exception here, depends on your use case        
    return json_response["some_other_value"] 

How can I recover from an exception and keep trying on the function it failed?

You could use a while loop for that:

def main(retries=100): # default value if no value is given
    result = functions_that_could_fail(retries)

    if result:
        logging.info("Finished successfully")
        functions_that_depend_on_result_from_before(result)
    else:
        logging.info("Finished without result")

def functions_that_could_fail(retry): 
    while(retry): # is True as long as retry is bigger than 0
        try: 
            # call all functions here so you just have to write one try-except block
            summary = get_summary()
            block_hash = get_block_hash()
            block = get_block()
            raw_transaction = get_raw_transaction()
        except Exception:
            retry -= 1
            if retry:
                logging.warning("Failed, but trying again...")
        else: 
            # else gets only executed when no exception was raised in the try block
            logging.info("Success")
            return summary, block_hash, block, raw_transaction

    logging.error("Failed - won't try again.")
    result = None

def functions_that_depend_on_result_from_before(result):
    [use result here ...]

So with the code from above you (and maybe also some other people who use your code) could start your program with:

if __name__ == "__main__":
    main()

    # or when you want to change the number of retries
    main(retries=50)

Java Interview Questions And Answers: Part-3, 13.2, the first catch block catches For- matException s (which occur ifinput of an invalid After the exception is handled, program control does not return to the throw point Once an exception is matched to a catch block, the code in that block  Here’s a quick guide on how to do this: Press Windows key + R to open up a Run dialog box. Then, type “control” and press Enter to open up the classic Control Panel interface. Inside Control Panel, use the search function (top-right) corner to search for ‘ internet options ‘.

C# 2012 for Programmers, program control continues with the first matching catch block (lines 78–81) in the catch, so line 80 outputs a message indicating the exception that occurred. At this point, program control returns to Main—any statements appearing after the​  In the above case, the program do not terminate unexpectedly. Instead, the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.

C# for Programmers, I'm trying to throw an exception (without using a try catch block) and my program finishes right after the exception is thrown. Is there a way that  Exceptions are occurred in situations like your program run out of the memory , file does not exist in the given path , network connections are dropped etc. More specifically for better understanding , we can say it as Runtime Errors occurs during the execution of a program that disrupts the normal flow of instructions.

continuing execution after an exception is thrown in java, Notice that the program did not terminate when the exception occurred because It is very important to note that after executing the catch block the control is not​  This feature is not available right now. Please try again later.

Comments
  • I'm not sure exactly what you mean by "who"? What are the options you envisage with that question?
  • @roganjosh it refers to either the main execution block (after if __name__...) or the same function who is thowing the exception by calling itself again.