Try catch

TypeScript allows for for the use of try... catch blocks in the same way that JavaScript does. Consider the following code:

try { 
    console.log(`1. attempting to parse JSON`); 
    JSON.parse(`abcd=234`); 
} catch (error) { 
    console.log(`2. try catch error : ${error}`); 
} finally { 
    console.log(`3. finally`); 
} 

Here, within the try block, we are logging a message to the console, and then attempting to call a function that may or may not throw an error. The JSON.parse function will throw an error if it is unable to parse the input string as valid JSON. In this code block, we are deliberately causing an error by using an invalid JSON string. If an error is thrown, the catch block will execute, and then the finally block will execute, irrespective of whether an error was thrown. The output of this code snippet would be as follows:

1. attempting to parse JSON
2. try catch error : SyntaxError: Unexpected token a in JSON at position 0
3. finally  

This output is as expected, and is logging the messages to the console in order.

We can also omit the error parameter from the catch block if we are not interested in what error has been thrown, as follows:

try { 
    console.log(`1. attempting to parse JSON`); 
    JSON.parse(`abcd=234`); 
} catch { 
    console.log(`2. caught`); 
} finally { 
    console.log(`3. finally`); 
} 

The output of this code would be as follows:

1. attempting to parse JSON
2. caught
3. finally