What is the main use of Try & Catch in Javascript? - javascript

I would like to know the main goal to use Try & Catch in Javascript, below is the example i am achieving
Should I need to let the program stop in case of error?
Why In programming I need to my application to continue running
however there is an error?
try {
if (typeof a != "number") {
throw new ReferenceError("The First argument is not a number");
} else if (typeof b != "number") {
throw new ReferenceError("The Second argument is not a number");
} else {
console.log(a + b);
}
} catch (error) {
console.log("Error:", error.message);
}
}
addTwoNums("10", 100);
console.log("It still works");

The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct

There are some things in java that require try and catch statements to function, for instance if you wanted to read a file java will prevent you from doing so unless error catching is used.
In your example whilst there is no harm in using try, it is simply unnecessary as there is no variability in the success of your function. Also, since there is no need to stop the program if the arguments are invalid, instead of throwing errors it might be preferable to instead halt the operation and return a warning.

Related

Catch exception not raised

Hey guys i wrote a code to raise exception ..The code is
<html>
<body>
<script>
var d =1;
try {
if(d == 2) {
console.log('fd');
}
} catch(e) {
console.log('catch');
}
</script>
</body>
</html>
When i give the value 2 for d the code inside try works but when the value is given 1 the code inside catch didnt works..
Can you tel me why its not working ??..Any help would be great ...Thanx
try...catch is for catching errors, not for handling conditional statements. if (d == 2) is perfectly valid and doesn't throw any errors, nor does the code within your conditional statement.
A catch clause contain statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch clause. If no exception is thrown in the try block, the catch clause is skipped.
— MDN's Notes on try...catch
If you want to do something if d isn't equal to 2, you can use else:
if (d == 2) {
...
}
else {
...
}
If you really want to use a try...catch statement here then you're going to have to throw an error. You can do this with JavaScript's throw statement:
try {
if (d != 2) {
throw "d is not equal to 2!";
}
}
catch (e) {
...
}
The catch block here will catch the error, and the e argument will be equal to our error string: "d is not equal to 2!".
try/catch is for handling errors. You're not generating an error, since your comparison is a valid comparison. An error is not the same as an if statement that returns false.
That's not the way a catch is intended to be used. The catch block will be visited once an exception is thrown. As an example, try to add the following else block to your if:
else { throw new Error; }
That said, it is not a good idea to control your flow by means of exceptions and I strongly discourage the use of such a solution in a production environment.
You need to throws the exception. Use throw "Exception" inside code like this:
try {
if(d == 2) {
console.log('fd');
}else{
throw "Exception";
}
} catch(e) {
console.log('catch');
}

Is there type of error in Javascript?

I would ask about java script error, is there type of error like php
or others,
example: In php we have notice, and Parse Error ..etc notice will not
be stop php execute, but parse will be stop execute php code
directly..
now is there js error like this, or what is the js classification
error .. I know we can handle error by try, catch ..,but is there
error in js was stooped script and others will not stop execute script
thank you
is there error in js was stooped script and others will not stop execute script
Not except for parsing/syntax errors, no.
JavaScript has exceptions. An exception exits the code in which it is thrown, and the code that called that, and so on until it's caught. If it isn't caught, then all currently-running functions are terminated and the error is logged to the web console.
So an exception (either one you throw explicitly or one that happens as a by-product of something you do) will either terminate all running functions (if not caught) or only terminate some code (if caught).
For example:
function foo() {
try {
bar(0);
}
catch (e) {
console.log("Caught exception");
}
}
function bar(a) {
if (a <= 0) {
throw new Error("'a' cannot be <= 0");
}
console.log("bar: a = " + a);
}
foo();
There, the code in bar following the exception is not run (we don't see "bar: a = 0") because an exception was throw, terminating bar. But foo's code continues, in the catch block, because foo caught the exception.
JavaScript is unusual in that you can throw anything, including a string, a number, etc. But if you want useful information, you usually throw Error:
throw new Error("Optional message here");
Since what you throw can be anything, you might be thinking there's a way to catch only certain things, but that's not the case. catch catches any exception that was thrown. So:
try {
throw "foo";
}
catch (e) {
}
try {
throw new Error();
}
catch (e)
}
try {
throw 42;
}
catch (e)
}
Note that those catch clauses are identical; they catch anything that was thrown. Of course, you can then inspect what you got and re-throw:
try {
// ...some code here that may throw any of several things...
}
catch (e)
if (typeof e === "string") {
// Handle it here
}
else {
throw e;
}
}
There we only handle exceptions that are strings, and not ones that are numbers, Error objects, etc.
You can create your own derived versions of Error if you like, although it's a bit more of a pain than it ought to be:
function MySpecificError(msg) {
this.message = msg;
try {
throw new Error();
}
catch (e) {
this.stack = e.stack;
}
}
MySpecificError.prototype = Object.create(Error.prototype);
MySpecificError.prototype.constructor = MySpecificError;
Then:
throw new MySpecificError("Something went wrong.");
Note that we had to fill in the code in MySpecificError to create the stack trace. (Also note that not all engines provide a stack trace, but if they do, this lets you use it.)
Some engines provide a few error types out of the box:
Error
RangeError (something was out of range)
ReferenceError (but usually that's something you'd let the engine throw)
TypeError (again)
SyntaxError (again)
Finally, it's worth noting that several things that would cause exceptions in other environments don't in JavaScript, mostly around math. For instance:
var result = 10 / 0;
In many non-JavaScript environments, that results in a runtime error (division by zero). In JavaScript, it doesn't; result gets the value Infinity.
Similarly:
var x = Number("I am not a number");
or
var x = parseInt("I am not a number", 10);
...doesn't throw a parsing error, it sets x to NaN ("not a number").
Yes. Javascript errors can have types, and there is a standard error type hierarchy. You can also write your code to "throw" things that are not error objects.
(In fact, since the catch clause in Javascript / ECMAScript does not discriminate based on the type of the exception, exception handling tends to be rather crude; i.e. "catch all errors" and then attempt to recover. Hence, to a first order, it doesn't matter what you throw.)
The ECMAScript 5.1 spec says that syntax errors are "early errors" and that they must be reported before the program is executed. An exception to this is syntax errors detected in code being run using eval. However, the spec doesn't say how early errors are to reported, or what happens afterwards. (At least, I don't think it does ...)
I believe that a common strategy for a Javascript parser/compiler/interpreter to skip to the enclosing block, and replace the affected code with code that throws an exception (e.g. SyntaxError) if it is run.
References:
http://www-archive.mozilla.org/js/language/js20-1999-02-18/error-recovery.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError
EcmaScript 5.1 - Errors

Uses of the finally statement

This is a very basic question. In Java I use the finally statement to close resources because "it's a good practice". I've been developing in Javascript and then in Node.js during some years and I've never used the finally statement. I know that in Node.js all of us follow the first parameter error handling pattern. Anyway, the 2 following snippets do the same:
try{
throw 123
}catch (e){
}finally{
console.log(1)
}
.
try{
throw 123
}catch (e){
}
console.log(1)
Both print 1.
Why is finally a keyword if it has no real benefit? The clean up code can be put inside the catch.
finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
Just a simple and straightforward example that shows the difference. There is a return that breaks the function completion, but the console.log in finally is called while the last console.log is skipped.
let letsTry = () => {
try {
// there is a SyntaxError
eval('alert("Hello world)');
} catch(error) {
console.error(error);
// break the function completion
return;
} finally {
console.log('finally')
}
// This line will never get executed
console.log('after try catch')
}
letsTry();
But try this:
try {
throw "foo"
} catch (e) {
throw "bar"
} finally {
console.log("baz")
}
console.log("quux")
If a second error is thrown from within the catch block, the code after the try...catch block will not run.
The finally block will always run, even if there is an error in the catch block.
Furthermore, the finally block runs even if a return or break statement stops the code in the try or catch block. return statements in the finally block override return statements in the try or catch block.
function foo() {
try {
return "bar";
} finally {
return "baz";
}
}
foo() // "baz"
oracle docs provide a good answer to this. Bottom line: finally gets called always! Even when you catch only one kind of exception (not the global catch), then finally gets called (after which your application probably breaks if there is no other catch)
the finally block is meant for a special purpose.
finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
Since it wont effect your business logic,Still it's compiler friendly,In memory aspects.
What if the try-block returns early or throws an exception that you don't handle? You would still want to free the resources you have allocated, right?
EDIT:
The answers to the question seem almost philosphical, there is some 'guessing' and basically 'we believe it should be useful, because it is there, so it should have a use', and 'even Oracle says so'. Or maybe it is there to help the programmer not 'to forget something' or 'accidently exit and not realize it'.
These are almost all valid reasons, but there is also a technical reason.
It helps avoiding code duplication in the cases mentioned, where (a) either the try or one of the catch blocks returns or (b) if within the catch block a second exception is thrown.
In these cases, if some cleanup code or any other code that still needs to be executed after the return and after the second exception, could be placed into the finally block, if it is to be executed both after the try and after the catch block.
You could still do it without the finally block, but the code would have to be duplicated, which the finally block allows you to avoid. This is where you really need it.
So if you are sure you do not miss it as a case of (a) or (b) you could still put the 'finally' code after the try/catch block and omit the finally clause.
But what if the situation changes? When you or another person change the code at some later point it could be forgotten to check if the cleanup code is now skipped in some situation.
So why not always put the cleanup code inside the finally block? And this is what is recommended and what many JavaScript programmers do.
You use it when you want to be sure your code is executed at the end, even if there was an exception during execution :
InputStream is = new FileInputStream("C://test.txt");
try {
//code...
} catch (Exception e) {
//code...
} finally {
is.close();
}
This is a very good question.
There is little to no reason to use finally in javascript, but I can imagine situations where it could be of practical use.
Suppose you have a webpage where you show a certain div after some user action, e.g. button clicked.
The div shows some logging for instance for the action the user requested.
After the action is complete (error or no error), you want to be sure to hide the div again. For that you can use the finally clause.
function doSomething() {
var d = document.getElementById("log");
show(d);
try {
... execute action ...
} catch(e) {
log(e);
} finally {
hide(d);
}
}
In general, as you mentioned, exceptions are less and less used in JavaScript in favor of error callbacks.
So, one could as well ask, what good uses are for exceptions in JavaScript in general.
The problem is with your example. There are cases when you don't want to catch the exception.
try {
if (Math.random() > 0.5) throw 123
}
finally {
console.log(1)
}
In these cases all you could do is rethrowing the exception if you don't want to use finally.
try {
if (Math.random() > 0.5) throw 123
}
catch (e) {
console.log(1)
throw e
}
console.log(1)
or maybe
try {
if (Math.random() > 0.5) throw 123
console.log(1)
}
catch (e) {
console.log(1)
throw e
}
Both alternative solutions lead to code duplication, that's why you need the finally keyword. It is used most of the time to free up unused resources. Forgetting about it may lead to unwanted locks or connections or memory leaks. I guess in some cases even a smart GC cannot prevent it.
In Java, if there's an Exception thrown that is not matched by any of the catch-blocks execution will break and any open resources will be left open.
The finally block will always be executed, even if an uncaught exception occurs.

How to fail with a fatal error or similar?

Is it possible to terminate script on a certain condition with a specific error message? Exceptions are not an option, as they can be catched, thus avoiding termination.
Update:
I'd prefer the universal approach, but if there's none, then it's for the in-browser JavaScript. Error should be silent, and the error message should only go into the browser error log.
If your code is inside a try statement, and you are looking for a way to stop it for certain errors, then I think you are looking for the finally block:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FStatements#The_finally_Block
From that site (and editing the annoying alert() for console.log()) you can find this example:
function f() {
try {
console.log(0);
throw "bogus";
} catch(e) {
console.log(1);
return true; // this return statement is suspended until finally block has completed
console.log(2); // not reachable
} finally {
console.log(3);
return false; // overwrites the previous "return"
console.log(4); // not reachable
}
// "return false" is executed now
console.log(5); // not reachable
}
f(); // alerts 0, 1, 3; returns false
Unfortunately, I only managed to accomplish this through the following ugly workaround:
var failWithFatalError; // A non-existent function
console.error (message + ' in ' + homebrewStackTraceFunction());
failWithFatalError();

How can I wrap these functions so their exceptions always get handled?

I've looked through the threads here on this subject and can't find what I want.
I have a bunch of functions that return string and I want them to not return a string if the input is bad and I don't want the program to exit either AND I don't want to wrap every call in try / catch.
function foo(num){
if(num > 5){
throw SomeException("Input too big")
}else{
return "bar"+num
}
}
I want to log an error like "6 is too big for foo", instead of exiting the program. But this will be kind of an api, so I don't want the user to have to try/catch every time they use
one of these functions. This is a nodejs script.
this works, but is a awkward:
f = {
command : function(cmd,arg){
try {
console.log(q[cmd](arg));
}
catch (e) {
console.log("Error: " + e + " for " + cmd);
}
},
foo : function(str){
throw ("foo error");
},
foo2 : function(str){
throw ("foo2 error");
}
};
f.command("foo",2);
f.command("foo2",3);
[[Edit]] It's a nodeJS script. Then make the API asynchronous. We do not do synchronous operations in nodeJS. Please conserve the event loop.
You can also rework your API to be asynchronous
function foo(num, cb){
if(num > 5){
cb(SomeException("Input too big"));
}else{
cb(null, "bar"+num);
}
}
foo(5, function(err, data) {
...
});
You can reference a public logger instance.
MyLibrary.errorHandler = defaultErrorHandler() || config.errorHandler
Then have the defaultErrorHandler be
function(error) {
if (console && console.log) { console.log(error.message); }
$("#errordiv").text(error.message);
}
function foo(num){
if(num > 5){
MyLibrary.errorHandler(new Exception("blargh"));
}else{
return "bar"+num;
}
}
If you're creating an API that others will use, and you want to signal that an error happened, well... throw an exception. If that exception doesn't get caught by the programmer using your API, that's their fault, not yours; on the other hand, if their code goes all wonky because your function does something really weird on an error, well... okay, that's still the other programmer's fault for not properly checking input coming into your API, but be a good citizen and help out their debugging by throwing that exception. They may dislike you for putting exceptions everywhere, but they'll hate you if your code just silently does really weird stuff instead of providing a good indication of what the error is.
I'd say log the error, too, but you're doing this in JavaScript, where there isn't any such facility.
And for the record, this is coming from a programmer who has used APIs that both do and do not throw exceptions on errors; the ones that do throw them are generally the ones I consider to be better-written.

Categories

Resources