Java Reference
In-Depth Information
More Examples of Exception Handling
Because Java accepts only strings as input in input dialog boxes and text fields, inputting
data into a string variable won't cause any problems. However, when we use the
methods parseInt , parseFloat ,or parseDouble to convert a numeric string into
its respective numeric form, the program may terminate with a number format error.
This is because the methods parseInt , parseFloat ,and parseDouble each throw a
number format exception if the numeric string does not contain a number. For
example, if the numeric string does not contain an int value, then when the method
parseInt tries to determine the numeric form of the integer string, it throws a
NumberFormatException .
EXAMPLE 11-4
This example shows how to catch and handle number format and division by zero
exceptions in programs that use input dialog boxes and/or text fields.
import javax.swing.JOptionPane;
public class ExceptionExample4
{
public static void main(String[] args)
//Line 1
{
int dividend, divisor, quotient;
//Line 2
String inpStr;
//Line 3
try
//Line 4
{
inpStr =
JOptionPane.showInputDialog
("Enter the dividend: ");
//Line 5
dividend = Integer.parseInt(inpStr);
//Line 6
1
1
inpStr =
JOptionPane.showInputDialog
("Enter the divisor: ");
//Line 7
divisor = Integer.parseInt(inpStr);
//Line 8
quotient = dividend / divisor;
//Line 9
JOptionPane.showMessageDialog( null ,
"Line 10:\nDividend = " + dividend
+ "\nDivisor = " + divisor
+ "\nQuotient =" + quotient,
"Quotient",
JOptionPane.INFORMATION_MESSAGE);
//Line 10
}
 
Search WWH ::




Custom Search