Handling Exceptions
The simplest way to handle Exceptions in java is
to throw them and let the program stop executing.
The more elegant way to handle Exceptions is to
catch them and to explicitly tell the program what to do
if something goes wrong. To do this, we use
try-catch. In the try block we
put the code where something exceptional might happen
during execution, as well as any statements that depend
on that code being successful (for example, we can't
read from a file if we weren't able to open it).
In the catch block we tell the program
what to do if the try was unsuccessful.
For example : use try-catch with parseInt()
in case the String doesn't represent a numerical value.
// Ask the user for a number
int number;
System.out.println(" Enter a number.");
System.out.print(" > ");
try {
number = Integer.parseInt(kb.readLine());
} // end try
catch (Exception e) {
System.out.print("Input Error: not an integer.");
} // end catch
Another example: use try-catch when opening a file
in case the file can't be found.
try {
// Create an input link to the file
inFile = new BufferedReader(
new InputStreamReader(
new FileInputStream(
new File (filename))));
int count = 0;
String s = inFile.readLine();
while (s != null) {
count = count + 1;
s = inFile.readLine();
} // end while
System.out.println("Lines in file = " + count);
} // end try
catch (Exception e) {
System.out.println(" Couldn't open file.");
System.out.println(" Did you type the right name?");
} // end catch