|
NOTA: La traducción de esta documentación es un esfuerzo personal y voluntario, no es un documento oficial de Sun Microsystems
ni Oracle ni está patrocinado por ninguna de estas empresas. Los documentos originales (en inglés) están disponibles en:
http://java.sun.com/docs/books/tutorial/.
Dirija cualquier comentario, petición, felicitación, etc. a tutorialesjava_@RROBA_codexion.com. |
Si desea ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesita que se traduzca algĂșn capĂtulo en concreto puede realizar una donación directa mediante Paypal:
|
This section describes how to use the three exception handler components — thetry,catch, andfinallyblocks — to write an exception handler. The last part of this section walks through an example and analyzes what occurs during various scenarios.The following example defines and implements a class named
ListOfNumbers. When constructed,ListOfNumberscreates aVectorthat contains 10Integerelements with sequential values 0 through 9. TheListOfNumbersclass also defines a method namedwriteList, which writes the list of numbers into a text file calledOutFile.txt. This example uses output classes defined injava.io, which are covered in Basic I/O.The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an//Note: This class won't compile by design! import java.io.*; import java.util.Vector; public class ListOfNumbers { private Vector vector; private static final int SIZE = 10; public ListOfNumbers () { vector = new Vector(SIZE); for (int i = 0; i < SIZE; i++) { vector.addElement(new Integer(i)); } } public void writeList() { PrintWriter out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + vector.elementAt(i)); } out.close(); } }IOException. The second boldface line is a call to theVectorclass'selementAtmethod, which throws anArrayIndexOutOfBoundsExceptionif the value of its argument is too small (less than 0) or too large (more than the number of elements currently contained by theVector).If you try to compile the
class, the compiler prints an error message about the exception thrown by theListOfNumbersFileWriterconstructor. However, it does not display an error message about the exception thrown byelementAt. The reason is that the exception thrown by the constructor,IOException, is a checked exception, and the one thrown by theelementAtmethod,ArrayIndexOutOfBoundsException, is an unchecked exception.Now that you're familiar with the
ListOfNumbersclass and where the exceptions can be thrown within it, you're ready to write exception handlers to catch and handle those exceptions.