Ruhul Mashbu Ruhul Mashbu - 20 days ago 4
Java Question

How to Use A Variable in Catch Block That is Declared in Try Block in Java?

How can I use a variable that was declared on the try block in catch block

try{
String str = "hi there";
}

catch(Exception e){
System.out.println(str + " from java");
}


this obviously goes out of scope and gives an undeclared error.... how can i use the str variable in catch block??

Answer
String str= null;

try{
    str= "hi there";
}

catch(Exception e){
  System.out.println(str + " from java");
}
Comments