Last Updated : 01 Aug, 2025
JavaScript uses throw to create custom errors and try...catch to handle them, preventing the program from crashing. The finally block ensures that code runs after error handling, regardless of success or failure.
try {
dadalert("Welcome Fellow Geek!");
}
catch (err) {
console.log(err);
}
Output: In the above code, we make use of 'dadalert' which is not a reserved keyword and is neither defined hence we get the error.
SyntaxThe try statement allows you to check whether a specific block of code contains an error or not. The catch statement allows you to display the error if any are found in the try block.
try { Try Block to check for errors. } catch(err) { Catch Block to display errors. }
Output: In the above code, our catch block will not run as there's no error in the above code and hence we get the output 'Value of variable a is: 10'.
Javascript Throws BlockThe throw StatementThe throw statement allows you to create custom error messages and throw exceptions manually.
throw new Error("Error message");
Key Point:
throw
creates a custom error.Error
.
try {
throw new Error('Yeah... Sorry');
}
catch (e) {
console.log(e);
}
Output:
The finally BlockThe finally Statement runs unconditionally after the execution of the try/catch block. Its syntax is
JavaScript
try {
console.log('try');
} catch (e) {
console.log('catch');
} finally {
console.log('finally');
}
Output: The Finally Block can also override the message of the catch block so be careful while using it.
Creating Custom Error TypesYou can create custom error types by extending the built-in Error class. This can be useful for more specific error handling.
JavaScript
//Driver Code Starts
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
//Driver Code Ends
function validateInput(input) {
if (input < 0) {
throw new ValidationError("Input must be a positive number");
}
return "Valid input";
}
//Driver Code Starts
try {
validateInput(-5); // Throws ValidationError
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
//Driver Code Ends
Output:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4