Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I access to a variable in try block in other try block?

http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/ In this link, there are some codes that access to a variable in try catch but when I try this in my server It doesn't work because It's out of scope. how can I do this?

try {
  const foo = "bar"
} catch (e) {
  console.log(e)
}

try {
  console.log(foo) -> is not defined
} catch (e) {
  console.log(e)
}
like image 787
Phillip YS Avatar asked Jun 01 '17 07:06

Phillip YS


People also ask

How do you access variables in try block?

Variables in try block So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.

Can try block include another try block?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

Can we use 2 try block?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.

Can we have one try block and multiple catch blocks?

Yes, we can define one try block with multiple catch blocks in Java.


1 Answers

The author of that post clearly did a mistake there––it happens to all of us.

So, the const declarations are block-scoped, like the docs say:

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.

That's why you cannot access it outside of the try-catch block.

To solve the problem:

  • Either use var instead of const:

    try {
      // When declared via `var`, the variable will
      // be declared outside of the block
      var foo = "bar"
    } catch (e) {
      console.log(e)
    }
    
    try {
      console.log(foo)
    } catch (e) {
      console.log(e)
    }
    
  • Or you can declare the variable outside of the try-catch, using let:

    // Maybe it's clearer to declare it with let and 
    // assign the value in the first try-catch
    let foo;
    try {
      foo = "bar"
    } catch (e) {
       console.log(e)
    }
    
    try {
      console.log(foo)
    } catch (e) {
      console.log(e)
    }
    
like image 179
Ionică Bizău Avatar answered Oct 24 '22 02:10

Ionică Bizău