Open In App

Why does exception still get thrown after catch in async function ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will try to understand when the exception is caught as well as thrown and later cached in the async function. Let us visualize our problem statement and its solution with the help of coding examples.

Example 1: We will create a new function that will throw an error, either using Promise.reject() method or with the throw statement. We will catch that throw error in another function which will be the async() function and then the rest part of our code also gets executed which is not required. 

Javascript




let exception_thrown_method = () => {
  return Promise.reject("Exception thrown...!!");
};
  
let catchException = async () => {
  let msg = await exception_thrown_method().catch((error) =>
    console.log("Caught Error: " + error)
  );
  console.log("Stop code's execution.....");
};
  
catchException();


Output:

Caught Error: Exception thrown...!!
Stop code's execution..... 

Example 2: In the async() function, we will create a new try/catch block. In the try block, we will call our first function which is throwing error. In the catch statement, we will catch the error which we have received from the first function. In the output, we will see that no extra line gets printed, only the catch statement line will be printed which is the desired result.

Javascript




<script>
    let exception_thrown_method = () => {
        return Promise.reject("Exception thrown...!!");
    };
  
    let catchException = async () => {
        try {
            await exception_thrown_method();
            console.log("Stop code's execution here only....!!");
        } catch (error) {
            console.log("Caught Error: " + error);
        }
    };
  
    catchException();
</script>


Output:

Caught Error: Exception thrown...!!

Example 3: We will do certain changes in catchException() async() method. In this async function, we will create a variable to call our method and later use the catch() method and then return “null” which seems to be like having a flag variable. Check whether the variable’s value is null writing an empty return statement. In the output, we will see no extra line gets printed, only the required line gets printed.

Javascript




<script>
    let exception_thrown_method = () => {
        return Promise.reject("Exception thrown...!!");
    };
  
    let catchException = async () => {
        let result = await exception_thrown_method().catch((error) => {
            console.log("Caught error: " + error);
            return null;
        });
  
        if (result === null) {
            return;
        }
        console.log("Stop code's execution here only...");
    };
  
    catchException();
</script>


Output:

Caught error: Exception thrown...!!


Last Updated : 27 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads