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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With