How javascript try...catch statement works - javascript

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.

Related

Error being thrown within async function gets caught

I want to use an async function instead of returning a promise, however to reject I need to throw an error like this:
async function asyncOperation() {
throw new Error("Terminate this application.");
}
(async () => {
try {
await asyncOperation();
} catch (e) {
console.error(e);
}
console.log("Nope, I am still running!"); // This will be printed regardless
})();
This means that to catch the reject I must put the function call within a try statement. By doing this, instead of terminating the application, I catch the error and I can continue afterwards.
This of course works as you would expect however I want to throw an error to actually terminate the application regardless if the function was called within a try statement or not.
How could I achieve this without checking the error within the catch statement?
I want to throw an error to actually terminate the application
No. Throwing exceptions is done only to be able to catch and handle them. If you really wanted to terminate your application no matter what (which would be a bad, untestable design), you'd just call process.exit() and be done with it.
I might have other errors that I do want to catch.
It sounds like what you actually want is to handle some of the thrown errors but let those that are unhandled terminate the application as usually - unless caught and handled further up in the chain. For that, you'll want to conditionally re-throw the exception:
try {
…
throw Object.assign(new Error("…"), {reason: X});
…
} catch (e) {
if (e.reason == Y)
console.error(e);
else
throw e;
}
console.log("I won't run after X errors!");
Notice that none of this actually has to do with async/await.

Is there an opposite of catch?

By running the following, you can run code if an error is thrown.
try {
// test
} catch (e) {
// error output
}
Is there a similar way to run code only if no error is thrown?
Sure there is, see the comment inline.
try {
// test
// No error is thrown if program control reaches here
} catch {
// error output
}
Consider using an additional try block in the "No error is thrown" part if you don't want the outer catch to handle any other errors.

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');
}

Testing URL schemes with try/catch

I'm trying to test URL schemes via javascript try/catch blocks but my catch blocks are not being executed. Safari just skips them entirely and I don't understand why?!
function open_twitter() {
if (!IS_IOS){ //made unequal IOS so that I could test it on my Macbook
try {
window.location = "twitter://"; //fails and should go to the catch block
} catch (e) { //skipped
try { //skipped
window.location = TWITTERRIFIC_URL_SCHEME; //skipped
} catch (e) { //skipped
null; //skipped
} //skipped
} //skipped
} else {
window.open(TWITTER_URL, "_blank");
}
}
Does anyone have an idea why this is happening?
I want the code to test the first URL scheme. If that isn't successful than it should (in theory) go to the catch block and run the code inside which is in my case a try block again with the next URL scheme to test and so on and so forth.
But this doesn't happen?! I'm really confused...
Try catch doesn't work exactly like what you wrote, You'll need to provide your catch with an exception, Else it doesn't know something bad happened.
See these docs : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
try/catch should be used as a simple test with your custom exception. For example,
try
{
if(false==false)
{
throw "myException"; // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
As you can see, The try should test for something and return an exception if some condition is met.

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.

Categories

Resources