Java Reference
In-Depth Information
￿ try {
If an exception occurs in the try block,
then control transfers immediately to the catch block and the code in the catch block
is executed.
...
} catch(Exception e) {
...
}⇒
￿ try {
...
} finally {
...
}⇒
The code in the finally block is always executed.
Exception that occurs when the user enters the wrong
type. For example, the program expects an integer and the user enters a double.
￿
InputMismatchException
Exception that occurs when the user accesses
an index of an array that is outside the elements of the array.
￿
ArrayIndexOutOfBoundsException
￿
ArithmeticException
An exception that occurs as a result of arithmetic opera-
tions, for example, division by 0.
￿
FileNotFoundException
An exception that occurs when the program tries to open
a file that does not exist.
￿ Exception
The main exception class. All other exception classes inherit from it.
￿ throw new Exception(" ... ")
Creates and throws a new exception.
￿ e.printStackTrace();
Prints the stack trace when the e exception occurs, that
is, the order of methods that were called.
￿ try(open a file) {
Opens a file. If an ex-
ception occurs, then control jumps over to the catch block. The file is closed auto-
matically at the end.
...
} catch(Exception e) {
...
}⇒
￿ if (fileChooser.showDialog(..., "Open") == JFileChooser.APPROVE OPTION)
{
Shows a file chooser dialog. The missing parameter is a reference to the par-
ent window.
...
}⇒
Gets a file object from a file
￿
File newFile = fileChooser.getSelectedFile();
chooser.
￿
Scanner inFile = new Scanner(file);
Creates a Scanner object from a file.
￿
String s = inFile.nextLine();
Reads a line from a file.
￿
String n = inFile.nextInt();
Reads an integer from a file.
True if there is a next line in the file.
￿
inFile.hasNextLine()
￿ inFile.hasNextInt()
True if there is a next integer in the file.
￿ inFile.close()
Closes the file.
￿ File newFile = new File("myFile.txt");
Creates an object of type File by
opening the file myFile.txt .
￿ PrintWriter fileWriter = new PrintWriter("myFile.txt");
Creates an ob-
ject of type PrintWriter .
￿ fileWriter.print("hello");
Prints hello to the file.
Closes the file.
￿
fileWriter.close();
 
Search WWH ::




Custom Search