Try-Catch-Finally

Basic error handling with try-catch-finally

BeginnerTopic: Error Handling
Back

JavaScript Try-Catch-Finally Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Basic try-catch
try {
    const result = 10 / 0;
    console.log('Result:', result);
} catch (error) {
    console.error('Error occurred:', error.message);
}

// Method 2: Try-catch with specific error
try {
    const data = JSON.parse('invalid json');
} catch (error) {
    if (error instanceof SyntaxError) {
        console.error('JSON parse error:', error.message);
    } else {
        console.error('Unknown error:', error);
    }
}

// Method 3: Try-catch-finally
try {
    console.log('Trying...');
    throw new Error('Something went wrong');
} catch (error) {
    console.error('Caught error:', error.message);
} finally {
    console.log('Finally block always executes');
}

// Method 4: Nested try-catch
try {
    try {
        throw new Error('Inner error');
    } catch (innerError) {
        console.error('Inner catch:', innerError.message);
        throw new Error('Outer error');
    }
} catch (outerError) {
    console.error('Outer catch:', outerError.message);
}

// Method 5: Error object properties
try {
    throw new Error('Test error');
} catch (error) {
    console.log('Error name:', error.name);
    console.log('Error message:', error.message);
    console.log('Error stack:', error.stack);
}

// Method 6: Custom error handling
function riskyOperation() {
    if (Math.random() > 0.5) {
        throw new Error('Random error');
    }
    return 'Success';
}

try {
    const result = riskyOperation();
    console.log('Result:', result);
} catch (error) {
    console.error('Operation failed:', error.message);
}

// Method 7: Multiple catch blocks (not supported, use if-else)
try {
    throw new TypeError('Type error');
} catch (error) {
    if (error instanceof TypeError) {
        console.error('Type error:', error.message);
    } else if (error instanceof ReferenceError) {
        console.error('Reference error:', error.message);
    } else {
        console.error('Other error:', error.message);
    }
}

// Method 8: Error in async function
async function asyncOperation() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Async error:', error.message);
        throw error; // Re-throw if needed
    }
}

asyncOperation().catch(error => {
    console.error('Unhandled async error:', error);
});
Output
Result: Infinity
JSON parse error: Unexpected token i in JSON at position 0
Trying...
Caught error: Something went wrong
Finally block always executes
Inner catch: Inner error
Outer catch: Outer error
Error name: Error
Error message: Test error
Error stack: Error: Test error
    at ...
Operation failed: Random error
Type error: Type error
Async error: Failed to fetch

Understanding Try-Catch-Finally

Try-catch-finally handles errors.

Try Block

Code that might throw
Execute normally if no error
Stop on error

Catch Block

Handle errors
Access error object
Prevent crash

Finally Block

Always executes
Cleanup code
Even if error thrown

Error Object

name: Error type
message: Error message
stack: Stack trace

Error Types

Error: Generic
TypeError: Type mismatch
ReferenceError: Undefined variable
SyntaxError: Parse error

Best Practices

Catch specific errors
Log errors properly
Use finally for cleanup
Re-throw if needed

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Table of Contents