Try-Catch-Finally
Basic error handling with try-catch-finally
JavaScript Try-Catch-Finally Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// 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);
});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 fetchUnderstanding Try-Catch-Finally
Try-catch-finally handles errors.
Try Block
Catch Block
Finally Block
Error Object
Error Types
Best Practices
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.
Practical Learning Notes for Try-Catch-Finally
This JavaScript program is part of the "Error Handling" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.