I'm learning java and one thing I've found that I don't like, is generally when I have code like this:
import java.util.*;
import java.io.*;
public class GraphProblem
{
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Error: Please specify a graph file!");
return;
}
FileReader in = new FileReader(args[1]);
Scanner input = new Scanner(in);
int size = input.nextInt();
WeightedGraph graph = new WeightedGraph(size);
for(int i = 0; i < size; i++)
{
graph.setLabel(i,Character.toString((char)('A' + i)));
}
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
graph.addEdge(i, j, input.nextInt());
}
}
// .. lots more code
}
}
I have an uncaught exception around my FileReader.
So, I have to wrap it in a try-catch to catch that specific exception. My question is does that try { }
have to encompass everything after that in my method that wants to use either my FileReader (in) or my Scanner (input)?
If I don't wrap the whole remainder of the program in that try statement, then anything outside of it can't access the in/input because it may of not been initialized or has been initialized outside of its scope. So I can't isolate the try-catch to just say the portion that intializes the FileReader and close the try statement immediately after that.
So, is it the "best practice" to have the try statement wrapping all portions of the code that are going to access variables initialized in it?
Thanks!