When dealing with some code JavaScript, we encounter several errors that need to be handled or removed. Errors occur for various reasons such as accessing an element out of bounds of the index. We need a proper way to deal with these errors to remove inconsistencies. Javascript throw statements or try-catch statements are some of the techniques that one can use to handle errors.
Try-Catch Block in JavaScript
The try-catch blocks in JavaScript are used to capture the errors and handle them. The try block encloses a piece of code that is doubtful of containing an error. The catch block is used to capture or catch that error to make further operations.
This simple mechanism allows developers to handle errors easily. The try block contains the possible problematic code that might cause an error during execution. If an exception occurs, the normal flow of the program is interrupted, and control is transferred to the associated catch block. The catch block contains the code that will be executed if such occurs.
The syntax of a try-catch block is as follows.
try {
// code doubted to contain an error goes here
}
catch (error) {
// code to handle the error goes here
}
The code within the try block is executed. If there’s no error, the catch block is never executed. But, if there’s an error, the control passes to the catch block.
The catch block also contains a parameter that can be used to further extract error information. The code written in the catch block is executed.
Developers can use the information provided by the caught exception to log the error by displaying a user-friendly message as well.
What is a JavaScript throw Statement?
The try-catch blocks are used to catch the already-known errors. But, the throw statement is a little different.
Throw statements are used to throw a custom error in JavaScript. When it is executed, the program flow is immediately interrupted, and the control is transferred to the nearest catch block.
One can define one’s errors according to particular conditions. The syntax is as follows:
throw error_expression;
where error_expression represents the error that is being thrown by the function. It can be a JavaScript string, number, boolean, or even an object.
Let us understand with an example example:
//making a function to check conditions and throw error function checkAge(age){ if(age<18){ throw new Error("Not Allowed to Vote!"); } else{ console.log("Allowed to Vote!") } } //declaring variables to check let age1=15; let age2=22; //calling the function checkAge(age2); checkAge(age1);
Output:
Allowed to Vote!
ERROR!
/tmp/NpMOpjTony.js:4
throw new Error("Not Allowed to Vote!");
^
Error: Not Allowed to Vote!
at checkAge (/tmp/NpMOpjTony.js:4:15)
at Object.<anonymous> (/tmp/NpMOpjTony.js:17:1)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
at node:internal/main/run_main_module:23:47
The code shows an error and doesn’t execute. The error occurs because the program is written to throw an error whenever the age is less than 18. But the program is not good enough to catch that error. This error has to be caught. Let us modify the code using the try-catch block using a try-catch block.
So, in the below example, we make use of the try-catch block wherever there’s a certainty of an error occurring:
//making a function to check conditions and throw error function checkAge(age){ if(age<18){ throw new Error("Not Allowed to Vote!"); } else{ console.log("Allowed to Vote!") } } //declaring variables to check let age1=15; let age2=22; //calling the function by handling them under try-catch block try{ checkAge(age2); checkAge(age1); } catch(error){ console.log(error.message); }
Output:
Allowed to Vote!
Not Allowed to Vote!
Now, the code has been executed and gives us the right output. The second age, age2 is less than 18 when passed through the function throws an error that is caught by the catch block. The error message from the throw statement is hence printed.
Let us look into another example:
//making a function to check conditions and throw an error function checkMarks(marks){ if(marks<50){ throw new Error("Not Applicable "); } else{ console.log("Applicable "); } console.log("check print"); } //declaring variables to check let marks1=90; let marks2=43; //calling the function by handling them under try-catch block //also check if the last statement of the function is executed or not try{ checkMarks(marks1); checkMarks(marks2); } catch(error){ console.log(error.message) }
Output:
Applicable
check print
Not Applicable
So, in this example, We have made a function to check the marks. If the marks are less than 50, an error is given which is caught by the catch block.
There is one important thing to observe. When marks greater than 90 are passed through the function, the else statement of the function executes, and the line below the else statement executes because it’s part of the function. But, when marks less than 50 are passed and throw is executed, no statement below the throw statement will execute. Hence, we have got the desired output.
The throw keyword does a similar thing in Java as well. Using it, a developer can communicate that something unexpected has happened, preventing the program from continuing with its normal execution.
Conclusion
Effective error handling is a critical aspect of JavaScript programming. In this article, we studied the error-handling methods of try-catch and throw statements. By using them for error handling, one can create robust and reliable applications that handle errors.