Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Throwing an Error in JavaScript</title> </head> <body> <script> function squareRoot(number) { // Throw error if number is negative if(number < 0) { throw new Error("Sorry, can't calculate square root of a negative number."); } else { return Math.sqrt(number); } } try { squareRoot(16); squareRoot(625); squareRoot(-9); squareRoot(100); // If error is thrown following line won't execute alert("All calculations are performed successfully."); } catch(e) { // Handle the error alert(e.message); } </script> </body> </html>