How to access a variable outside a try catch block
The error is that you are not returning anything in the case where an exception is thrown.
try the following:
public boolean checkStatus(){
boolean result = true; // default value.
try{
InputStream fstream = MyRegDb.class.getClassLoader().getResourceAsStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
strLine = br.readLine();
// Print the content on the console
System.out.println (strLine);
ind.close();
if(strLine.equals("1")){
result = false;
}else{
result = true;
}
}catch(Exception e){}
return result;
}
How can I access a variable from outside the try catch block?
Scope of a variable: As a general rule, variables that are defined within a block are not accessible outside that block.
Lifetime of a variable: Once a variable loses it scope, Garbage collector will takes care of destroying the variable/object. The lifetime of a variable refers to how long the variable exists before it is destroyed.
try {
byte len = (byte) passLength();
}
In your above example, the variable len
is declared inside the try block, its scope is only within the try block and can't be accessed outside the try block.
You should declare the len
variable even before the try block, so that it can be accessed in the finally block.
byte len = Byte.MIN_VALUE; //This value is for dummy assignment
try {
len = (byte) passLength();
} catch(Exception inputMismatchException) { // Avoid using variable name starts with Capitals
System.out.println("Error, please input a proper number");
} finally {
String result = passGen(len, chars);
System.out.println(result);
}
Hope, this will be helpful :)
Using variable outside of try catch block (Java)
To resolve the compilation error, declare the result
variable only before the try-catch block:
List<String> result;
try( Stream<Path> walk = Files.walk(Paths.get("data"))){
result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
}
catch(Exception e){
e.printStackTrace();
result = null;
}
However, note that accessing the result
variable after the try-catch block (your result.listiterator()
statement) without checking that it's not null may throw a NullPointerException
.
You should be asking yourself why you are catching any exception and expecting everything to work fine.
Java how to access a variable outside the try-catch block
You should declare the variable before the try block (in order for it to still be in scope after the try-catch blocks), but give it an initial value :
class factorial{
public static void main(String[] args){
int num = 0;
try {
num = Integer.parseInt(args[0]);
}
catch(Exception e){
System.out.println(e+" Cannot convert arg to int, exiting..");
}
System.out.println(num );
}
}
how can I access to a variable in try block in other try block?
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
, usinglet
:// 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)
}
How to use var - variable outside of try-catch block
Thanks to Evk for the good answer (But in the comments...)
I declare myValue as an object:
string myValue;
try
{
myValue = from el in keyValueList select el.Value;
}
catch (Exception ex)
{
}
Using variable outside Try-Catch
Your example is a perfect illustration of why writing
catch (Exception){}
is a very bad practice.
When you catch an exception, you are supposed to do something about it. If you do not know what to do with an exception in a particular method of your code, don't catch the exception in that method.
If you always need a customer, even when its retrieval causes an exception, add some code to the catch
block to set customer
variable to some default object:
try {
...
} catch (Exception) {
customer = Customer.Unknown;
}
This assumes that Customer
has a property Unknown
of type Customer
with some default behavior.
Comment: Needed to warn the upper level of my code. Just, when I create an instance, create it, but warn the arguments where wrong. Could you recommend me some better approach?
Make a factory for validating users while creating them:
class CustomerCreationResult {
public Customer Customer() { get; set; }
public CustomerCreationError Error() { get; set; }
}
class CustomerFactory {
public CustomerCreationResult CreateCustomer(String name, int age) { ... }
}
Now you can create your customers as follows:
var r = myCustomerFactory.CreateCustomer(name, age);
if (r.getError() != null) {
... // Present the error
}
Customer customer = r.Customer;
...
Related Topics
Spring Security Configuration Filter Any Requests Except a Specific Endpoint
Remove End of Line Characters from Java String
Optimizing Multiple If-Else Condition in Java
Java Spring @Scheduled Tasks Executing Twice
Batch Inserts Using JPA Entitymanager
Keep the Order of the Json Keys During Json Conversion to Csv
How to Efficiently Return the Max Possible Integer With a Given Number of Digits
In Activity.Oncreate(), Why Does Intent.Getextras() Sometimes Return Null
How to Sort Json Object in Java
Refactor Multiple If' Statements in Java-8
Multiple Queries Executed in Java in Single Statement
Javac Option to Compile All Java Files Under a Given Directory Recursively
How to Delete the Content of Text File Without Deleting Itself
Type Safety: Unchecked Cast from Object to Arraylist<Myvariable>