Error Handling with Try-Catch

Beginner
90 XP
35 min
Lesson Content

Error Handling with Try-Catch

Errors are inevitable in programming. JavaScript provides try-catch blocks to handle errors gracefully, preventing your program from crashing.

Basic Try-Catch

try {
  // Code that might throw an error
  let result = riskyOperation();
  console.log(result);
} catch (error) {
  // Handle the error
  console.log('An error occurred:', error.message);
}

Common Error Types

  • ReferenceError - Variable doesn't exist
  • TypeError - Wrong data type operation
  • SyntaxError - Invalid code syntax
  • RangeError - Number out of valid range

Try-Catch-Finally

try {
  // Risky code
  processData();
} catch (error) {
  // Handle error
  console.error('Error:', error);
} finally {
  // Always runs, even if error occurs
  cleanup();
}

Throwing Custom Errors

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero!');
  }
  return a / b;
}

try {
  let result = divide(10, 0);
} catch (error) {
  console.log(error.message); // 'Cannot divide by zero!'
}

Error Object Properties

  • error.message - Error description
  • error.name - Error type
  • error.stack - Stack trace (where error occurred)

Best Practices

  • Use try-catch for code that might fail
  • Provide meaningful error messages
  • Log errors for debugging
  • Don't catch errors you can't handle
  • Use finally for cleanup code
Example Code

Handle errors gracefully in your code

// Function that might throw an error
function safeDivide(a, b) {
  if (b === 0) {
    throw new Error('Division by zero is not allowed');
  }
  return a / b;
}

// Try-catch example
function calculate(a, b) {
  try {
    let result = safeDivide(a, b);
    console.log('Result:', result);
    return result;
  } catch (error) {
    console.log('Error caught:', error.message);
    return null;
  } finally {
    console.log('Calculation attempt completed');
  }
}

// Test cases
console.log('Test 1: 10 / 2');
calculate(10, 2);

console.log('\nTest 2: 10 / 0');
calculate(10, 0);

// Handling different error types
try {
  let x = undefinedVariable;
} catch (error) {
  console.log('\nError type:', error.name);
  console.log('Error message:', error.message);
}

Expected Output:

Test 1: 10 / 2
Result: 5
Calculation attempt completed

Test 2: 10 / 0
Error caught: Division by zero is not allowed
Calculation attempt completed

Error type: ReferenceError
Error message: undefinedVariable is not defined
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code