Error Handling
try / catch / finally. Throw real Error objects, not strings.
10 programs · open one, then the next
Start with Try-Catch-Finally- 01Try-Catch-FinallyBeginnerBasic error handling with try-catch-finallyOpen example →js// Method 1: Basic try-catch try { const result = 10 / 0; console.log('Result:', result);
- 02Custom ErrorsIntermediateCreate and use custom error classesOpen example →js// Method 1: Custom error class class CustomError extends Error { constructor(message, code) { super(message);
- 03Error PropagationIntermediatePropagate errors through call stackOpen example →js// Method 1: Re-throw error function level1() { try { level2();
- 04Async Error HandlingIntermediateHandle errors in async operationsOpen example →js// Method 1: Async/await with try-catch async function fetchData() { try { const response = await fetch('https://api.example.com/data');
- 05Global Error HandlingIntermediateHandle errors globallyOpen example →js// Method 1: Window error handler window.addEventListener('error', function(event) { console.error('Global error:', event.message); console.error('File:', event.filename);
- 06Error LoggingIntermediateLog errors effectivelyOpen example →js// Method 1: Simple error logger class ErrorLogger { log(error, level = 'error') { const logEntry = {
- 07Error Retry LogicIntermediateImplement retry logic for failed operationsOpen example →js// Method 1: Simple retry async function retryOperation(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try {
- 08Defensive ProgrammingIntermediateWrite defensive code to prevent errorsOpen example →js// Method 1: Input validation function processUserInput(input) { if (typeof input !== 'string') { throw new TypeError('Input must be a string');
- 09Error RecoveryAdvancedRecover from errors gracefullyOpen example →js// Method 1: Fallback values function fetchWithFallback(url, fallback) { return fetch(url) .then(response => response.json())
- 10Error TestingIntermediateTest error handlingOpen example →js// Method 1: Test error throwing function testErrorThrowing() { try { throw new Error('Test error');