简体   繁体   中英

Can we get variable that in Try from catch?

Just a simple question here. Can we get the variable that declared inside the Try from catch?

Eg.

Try {
.....
String s7 = ftpfile1.getName().toString();
.....
}
catch {
System.out.println(s7);
}

I know this is not the way to getting the string s7 . So, I want to ask that is there any possible way or what do I need to do to get the s7 in the catch? Any examples, related post or answers to share?

Expected result: Can get s7 in the catch.

Thanks for viewing, comments and answers.

ps Java Newbie.

The scope of the s7 variable is just inside the try{} block. For the variable s7 be usable inside the catch{} block you need to increase the scope of the variable. You can do that by moving the declaration outside the try:

String s7 = null;
try {
    .....
    s7 = ftpfile1.getName().toString();
    .....
} catch (Exception e) {
    if (s7 != null) {
      System.out.println(s7);
    } else {
      // s7 is null ...
    }
}

You also need to initialize s7 to some value, else the compiler will warn you about the use of an uninitialized variable. That's because exceptions break normal workflow, and if an exception is thrown your variable s7 could have not been initialized.

In Java code is organized in blocks defined by { and } . Members defined inside the block are not accessible from outside.

{//Block 1
   String outside;
    { //Block 2
      String value = "in block";
      outside = "new Value";
    }
}

In above example we have two blocs, we can access to structures in inner blocks. We can decorate those block to create a class and method.

class MyClass {

 String outside;

 void method() {
     String value = "in block";
     outside = "new Value";
 }

}

Same rule obey to try/catch clause.

String s7;

try {
   s7 = ftpfile1.getName().toString();
   //.....
} catch(Exception e) {
  System.out.println(s7);
}

To find out more read: Blocks and Statements

You can define the variable before the try block, then you can access it withing the catch/finally block

String s7 = null

Try {
.....
s7 = ftpfile1.getName().toString();
.....
}
catch {
System.out.println(s7);
}

just declare your variable before the try block.

String s7 = null;

Try {
s7 = ftpfile1.getName().toString();
}
catch {
System.out.println(s7);
}

You need to delcare s7 outside the try.

String s7 = null;
Try {
  .....
  s7 = ftpfile1.getName().toString();
  .....
}
catch {
  System.out.println(s7);
}

try Like this,

String s7 = null;
    Try {
    .....
    s7 = ftpfile1.getName().toString();
    .....
    }
    catch {
    System.out.println(s7);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM