The first step in constructing an exception handler is to enclose the code that might throw an exception within atryblock. In general, atryblock looks like the following.The segment in the example labeledtry { code } catch and finally blocks . . .codecontains one or more legal lines of code that could throw an exception. (Thecatchandfinallyblocks are explained in the next two subsections.)To construct an exception handler for the
writeListmethod from theListOfNumbersclass, enclose the exception-throwing statements of thewriteListmethod within atryblock. There is more than one way to do this. You can put each line of code that might throw an exception within its owntryblock and provide separate exception handlers for each. Or, you can put all thewriteListcode within a singletryblock and associate multiple handlers with it. The following listing uses onetryblock for the entire method because the code in question is very short.If an exception occurs within theprivate Vector vector; private static final int SIZE = 10; PrintWriter out = null; try { System.out.println("Entered try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + vector.elementAt(i)); } } catch and finally statements . . .tryblock, that exception is handled by an exception handler associated with it. To associate an exception handler with atryblock, you must put acatchblock after it; the next section shows you how.