JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do try, catch, and finally work in JavaScript?

Asked on Aug 27, 2024

Answer

The "try", "catch", and "finally" blocks in JavaScript are used for handling exceptions and executing code regardless of whether an error occurs or not.
<!-- BEGIN COPY / PASTE -->
        try {
            // Code that may throw an error
            let result = riskyOperation();
            console.log("Operation successful:", result);
        } catch (error) {
            // Code to handle any errors
            console.error("An error occurred:", error.message);
        } finally {
            // Code that runs regardless of the outcome
            console.log("Execution completed.");
        }
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "try" block contains code that might throw an error.
  • The "catch" block executes if an error occurs in the "try" block, allowing you to handle the error.
  • The "finally" block executes after the "try" and "catch" blocks, regardless of whether an error was thrown or not.
  • Use "finally" for cleanup actions that must run after the try-catch process.
✅ Answered with JavaScript best practices.
← Back to All Questions