Javascript nested exception handelling - javascript

I was trying few examples about exception handelling in javascript using nested try..catch. The code within the inner try block throws an error but instead of the inner catch block handelling the code, the exception is being caught by the outer catch block. I didnt understand that part
This i read on the MDN documentation but it doesnt go with the example i tried:
"Any given exception will be caught only once by the nearest enclosing catch-block
unless it is re-thrown. Of course, any new exceptions raised in the "inner" block (because
the code in catch-block may do something that throws), will be caught by the "outer" block".
function a() {
try {
d()
function d() {
try {
let user = "hello"
let user = {name: 'bruce'}
} catch (err) {
console.log(err, "inside the function err")
}
}
} catch (err) {
console.log(err, "Error caught")
}
}
a()
The error:
SyntaxError: Identifier 'user' has already been declared, 'Error caught'
Considering the above statement error should be caught in inner catch block then why is it getting caught in the outer catch block
I expected the error should be caught inside the 'inner catch block'(i.e, err,"inside the function err") but instead its getting caught by the 'outer' one (i.e,err,"Error Caught").

Here in your snippet , When you declare let user , let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
When you keep the same variable name , it is considered an error when the program compiles , while try catch detects the error at run-time . Therefore , your program does not get compiled fully and it gives the error at compile time due to duplicate variable name .
Hope you get the point .
Instead try out the following code .
function a() {
try {
d()
function d(user) {
try {
JSON.parse(user);
} catch (err) {
console.log(err, "inside the function err")
}
}
} catch (err) {
console.log(err, "Error caught")
}
}
a()
It will give you your expected output .

Related

Why isn't 'error' variable reassignment functionally scoped inside of catch{} block?

I am working with try-catch blocks in JavaScript and have run into some variable scoping behaviour I don't completely understand.
I understand that console.log(boo) prints 20 to the console because the variable has been declared with the var keyword and hence it is functionally scoped (i.e. not block scoped to the catch block).
However, I don't understand why the err variable isn't also scoped to the IIFE in the same way as the boo variable. Therefore I don't understand why it is undefined outside of the catch block.
(function() {
try {
throw new Error();
} catch (err) {
var err = 10;
var boo = 20;
console.log(err); //'10' (as I expect)
}
// Why doesn’t this log '10' ???
console.log(err); // 'undefined' (but I expected '10')
console.log(boo); // '20' (as I expect)
})();
I found the answer.
It is because the exception 'identifier' (which is the 'err' variable in the example above) is not available after the catch block has finished executing. This seems like a special case of handling scoping in JS and is definitely a 'gotcha' until one does some digging.
Hopefully this helps someone else!
From the docs:
While var hoists the symbol to the top of the function block, the catch clause's "argument" is local to the clause. Since you have named the hoisted value the same as the clause symbol, this can be rather confusing. In essence, your code is the same as:
(function () {
var err;
var boo;
try {
throw new Error();
} catch (err) {
err = 10; // Set the catch's "local" `err` identifier to `10`
boo = 20; // Set the hoisted `boo` identifier to `20`
console.log(err);
}
console.log(err); // The hoisted `err` was never set.
console.log(boo); // ’20’ (as I expect)
})();
You might also think of the err in the catch-clause like a parameter to a function/clause; its scope is local to the function and has nothing to do with the global scope (whether or not the symbol exists in global scope).

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

What if I use "throw" in "catch"?

function f(){
try{
if (/*some codes*/) throw false;
return true;
}
catch(x){
if (x===false) return false;
throw x;
}
}
Here,what does "throw x" mean? It seems codes in "catch" won't run twice.
If you had something like:
try {
try {
//something
} catch(x) {
throw x;
}
} catch(x) {
//handle it
}
The throw in the inner catch would cause the outer catch to execute
It means it throws the exception to the calling function, which will execute its catch block in case there is one defined.
For example, in the below code, you log the exception in the callthis() function, but you would like the calling function (init()) to decide how to handle it. Hence you re-throw the exception, which gets bubbled up.
window.onload = init();
function init(){
try {
callthis();
} catch(e) {
alert('init - calling function');
}
}
function callthis(){
try {
var x = null.split(','); //inducing an error
} catch(e){
alert('callthis - called function');
throw e;
}
}
Fiddle
When you have a try/catch block in Javascript, the catch block will take any error that can happen in try block. The keyword throw is used to throw a error to the superior scope (who call the function for sample) passing the error on it (exception) that will be taken by the catch block. In the catch you can take as a first argument the exception. In your code, you get a error the throw using throw x where x is the exception. The caller will get the x as a argument on the catch block.
function K()
{
try
{
f();
}
catch(ex)
{
// handle any exception thrown by f();
}
}
If you or the runtime throw an error on catch block, it will be passed to superior scope, in this case, the scope who called K function.
This is the way you would both catch an exception and bubble it up the stack for users to handle.
I wouldn't like seeing this code. You've already caught the exception and set the return value to false. Why throw the exception? Let the users check the return value and decide what to do next. Your catch block does nothing useful.
If you catch an exception, you should consider it handled and shouldn't rethrow it. The only exception would be wrap a checked exception as unchecked.
If you can't handle it, and logging is NOT considered handling, I'd prefer to add the throws clause to the method signature and let it bubble out of the method.

Can syntax errors be caught in JavaScript?

MDN states:
A SyntaxError is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.
But if there's a syntax error, how could the program even run in the first place?
How can JavaScript syntax errors even be caught?
You cannot use try-catch blocks to handle syntax errors as they are thrown while the code is being parsed and not while it's running.
However you can use window.onerror and figure out that there's an error. You must ensure that the onerror function is defined in a separate script tag and not in the tag in which the error may be present!
Eg:
This will not work, because the script is yet to start running when the error is thrown:
<script>
window.onerror = function (e) {
console.log('Error: ', e);
};
console.log('a'');
</script>
This will work:
<script>
window.onerror = function (e) {
console.log('Error: ', e);
};
</script>
<script>
console.log('a'');
</script>
jsfiddle demo
In the JS world, SyntaxError CAN be a runtime exception. This can arise, for instance, when trying to parse a JSON response that isn't JSON format. The server can send back lots of types of responses, so if you send a HTML body response to your request that's expecting JSON in the body, you're going to get a SyntaxError thrown in the JS. In such a case, you would get an error message that looks something like this: SyntaxError: JSON Parse error: Unrecognized token '<'.
But there are other runtime SyntaxErrors you could get as well. Mozilla has a list of some here: SyntaxErrors for JSON parsing
You may want to catch these in your code. You can do so with a generic try/catch block like this:
try {
JSON.parse('<html></html>');
} catch (e) {
console.log("I catch & handle all errors the same way.");
}
OR you can look for the SyntaxError specifically:
try {
JSON.parse('<html></html>');
} catch (e) {
if (e instanceof SyntaxError) {
console.log("I caught a pesky SyntaxError! I'll handle it specifically here.");
} else {
console.log("I caught an error, but it wasn't a SyntaxError. I handle all non-SyntaxErrors here.");
}
}
Mozilla has even more info on JS errors and handling them.
It's runtime errors that can be caught with try-catch, not syntax errors (if you eval your code you can handle syntax errors in the evaled code but that's just weird).
I'd recommend you read these:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#try...catch_Statement
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#Exception_Handling_Statements
You can catch programmer-generated and runtime exceptions but you cannot catch JavaScript syntax errors, though you may handle them in some browsers using window.onerror.
This is taken from the book JavaScript- The Complete Reference by Thomas-Powell which I like very much. You can refer to the code examples in that book.
You specifically cannot catch parser-generated SyntaxErrors since they are thrown by the parser, which has no idea what try/catch blocks do. More info on that - Learning how programming languages work
There is a way to catch SyntaxErrors that are generated during code execution. This method is slow, and I would not recommend it. You can catch SyntaxErrors using eval().
var code = `function() {
doSomething()
somethingElse()
var x = 5 + 5
// No ending curly brace` // The code to be run using eval
try {
eval(code) // Try evaluating the code
} catch (e) {
if (e.name !== 'SyntaxError') throw e // Throw the error if it is not a SyntaxError
console.log('A SyntaxError has been caught\n\nDetails:\n' + e) // It is a SyntaxError
}
Alternatively, you could use new Function(), which is up to 93% faster - https://jsben.ch/1HLQ1
var code = `function() {
doSomething()
somethingElse()
var x = 5 + 5
// No ending curly brace` // The code to be run using eval
try {
new Function([], code) // Try evaluating the code
} catch (e) {
if (e.name !== 'SyntaxError') throw e // Throw the error if it is not a SyntaxError
console.log('A SyntaxError has been caught\n\nDetails:\n' + e) // It is a SyntaxError
}

How javascript try...catch statement works

I am trying to test in browsermob if certain input field work or not. I am attempting to use a try...catch statement which I have never used before. I know that the form is:
try {
//some code
} catch (){
//some error code
};
What exactly is supposed to be put in the parenthesis after the catch statement?
When I try to use the statement it runs everything through the catch statement no matter if it is not an error. What am I doing wrong?
See the “try...catch statement” guide on MDN.
In short, try/catch is used to handle exceptions (which are "thrown" using the throw statement). The syntax for try/catch is:
try {
// Code
} catch (varName) { // Optional
// If exception thrown in try block,
// execute this block
} finally { // Optional
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
varName is available to the scope of the catch block only. It refers to the exception object which was thrown (which could be any type of object, e.g. a String, but is usually an Error object).
The try catch statement is used to detected for exceptions/errors that are raised inside the try-block. In the catch block you can then react on this exceptional behavior and try to resolve it or get to a safe state.
You got the statement almost right:
try {
// code that may fail with error/exception
} catch (e) { // e represents the exception/error object
// react
}
Consider the following examples:
try {
var x = parseInt("xxx");
if(isNaN(x)){
throw new Error("Not a number");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
try {
// some code
if(!condition){
throw new Error("Something went wrong!");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
the stuff inside try {...} is what you want to execute. The stuff in catch() { ... } is what you want to execute if you get any javascript errors from anything executed in the try {...}
catch {...} only executes if there is a javascript error in the try {...} block. You can find out what the error is by doing for example this:
try {
// do something
} catch (err) {
alert(err);
}
According to ECMAScript specifications,
try {
// Code
} catch (varName) { // optional if 'finally' block is present.
if (condition) { // eg. (varName instanceof URIError)
// Condition (Type) specific error handling
}
else {
// Generic error handling
}
} finally { // Optional if 'catch' block is present.
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
the code that is likely to throw an exception goes into try { }, The code to be run when an exception is thrown, comes into catch() { }. In catch() you can specify which exceptions you want to catch, and in which automatic variables to put it.
finally { } is always run, regardless whether exception was thrown or not.

Categories

Resources