This is not a problem with try / catch blocks per se. The problem is related to changing the variables and that you should have a try / catch block due to a checked exception and therefore create a new scope.
You also have another option - declare the thrown exception (s) as throws from your method.
public static void main(String[] args) throws IOException {
This is completely legal for the main method.
If you want to handle the exception, as in a larger program. You can define a specific try / catch around the problematic block of code and use a variable outside the scope by declaring a variable outside this scope, as many have answered:
FileReader fr = null; // must be initialized here if the exception handling code // does not exit the method try { fr = new FileReader(fileName); } catch (IOException ex) { // log, print, and/or return // if you return or exit here then subsequent code can assume that fr is valid }
You can also move the code to another method that deals with the exception:
private static FileReader openReader(String fileName) { try { return new FileReader(fileName); } catch (IOException ex) { // log/print exception return null; // caller must then expect a null // or throw new RuntimeException(...); // throw a RuntimeException of some kind (may not be good practice either) } }
You can also move the file processing code to another method. This can be better and allow you to more correctly follow the open / closed in the final idiom:
FileReader fr = null; try { fr = new FileReader(fileName); Scanner input = new Scanner(fr); processInput(input); } catch (IOException ex) { // log/print exception } finally { if (fr != null) { try { fr.close(); } catch (IOException ex) { // empty } } } private static void processInput(Scanner in) throws IOException { // ...processing here }
In the next part, you can use a third-party library (Apache File Utils) or write a simple method to provide a static safe closing method that does not throw exceptions.
You really should take a look at breaking up large methods into smaller units, and this will often give you a clearer way of handling exceptions.
Kevin brock
source share