Programming Java using JBuilder - Part IV - Developing Comprehensive Projects
Programming Java using JBuilder - Part IV - Developing Comprehensive Projects
Chapter 14 Internationalization
Chapter 15 Multithreading
Chapter 16 Multimedia
Chapter 18 Networking
593
13
Exception Handling
Objectives
• Understand the concept of exception handling.
Introduction
594
drawn from the savings account and before the money is
deposited in the checking account, the customer will lose
money.
You can handle this error in the following code using a new
construct called the try-catch block to enable the program
to catch the error and continue to execute.
public class Test
{
public static void main(String[] args)
{
try
{
System.out.println(3/0);
}
catch (Exception ex)
{
System.out.println("Error: " + ex.getMessage());
}
System.out.println("Execution continues");
}
}
595
graphics.) An event may be ignored in graphics programming,
but an exception cannot be ignored. In graphics programming,
a listener must register with the source object. External
user action on the source object generates an event, and the
source object notifies the listener by invoking the handlers
implemented by the listener. If no listener is registered
with the source object, the event is ignored. However, when
an exception occurs, the program may terminate if no handler
can be used to deal with the exception.
Figure 13.1
596
Examples are ClassNotFoundException,
CloneNotSupportedException, IOException, RuntimeException,
and AWTException,
597
In Java, the statement currently being executed belongs
either to the main method or to a method invoked by another
method. The Java interpreter invokes the main method for a
Java application, and the Web browser invokes the init
method for a Java applet. In general, every method must
state the types of exceptions it might encounter. This
process is called claiming an exception, which simply tells
the compiler what might go wrong.
Claiming Exceptions
Throwing Exceptions
In the method that has claimed the exception, you can throw
an object of the exception if the exception arises. The
following is the syntax to throw an exception:
598
throw new TheException();
Catching Exceptions
599
no handler is found in the chain of methods being invoked,
the program terminates and prints an error message on the
console.
Figure 13.3
600
This returns a localized description of the Throwable
object. Subclasses of Throwable can override this method
in order to produce a locale-specific message. For
subclasses that do not override this method, the default
implementation returns the same result as getMessage().
Locale-specific issues are addressed in Chapter 14,
"Internationalization."
• public void printStackTrace()
601
// Data fields for numerator and denominator
private long numerator = 0;
private long denominator = 1;
/**Default constructor*/
public Rational()
{
this(0, 1);
}
while (remainder != 0)
{
t1 = t2;
t2 = remainder;
remainder = t1%t2;
}
return t2;
}
/**Return numerator*/
public long getNumerator()
{
return numerator;
}
/**Return denominator*/
public long getDenominator()
{
return denominator;
}
602
if (secondRational.getNumerator() == 0)
throw new RuntimeException("Denominator cannot be zero");
long n = numerator*secondRational.getDenominator();
long d = denominator*secondRational.getNumerator();
return new Rational(n, d);
}
603
public class TestRationalException
{
// Main method
public static void main(String[] args)
{
// Create three rational numbers
Rational r1 = new Rational(4, 2);
Rational r2 = new Rational(2, 3);
Rational r3 = new Rational(0, 1);
try
{
System.out.println(r1+" + "+ r2 +" = " + r1.add(r2));
System.out.println(r1+" - "+ r2 +" = " + r1.subtract(r2));
System.out.println(r1+" * "+ r2 +" = " + r1.multiply(r2));
System.out.println(r1+" / "+ r2 +" = " + r1.divide(r2));
System.out.println(r1+" / "+ r3 +" = " + r1.divide(r3));
System.out.println(r1+" + "+ r2 +" = " + r1.add(r2));
}
catch (Exception ex)
{
System.out.println(ex);
}
Figure 13.4
Example Review
604
throw new RuntimeException("Denominator cannot be zero");
Figure 13.5
605
Figure 13.6
Example Review
try
{
// Perform selected operation
switch (operator)
{
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
}
Figure 13.7
606
Rethrowing Exceptions
607
[BX] If one of the statements causes an exception that is
not caught in any catch clause, the other statements
in the try block are skipped, the finally clause is
executed, and the exception is passed to the caller
of this method.
608
Figure 13.8
JApplet ActionListener
NegativeAmountException
Account
-account: Account
-transactionAmount: double -id: int
-transactionType: String -balance: double AccountApplet
Exception
+getId(): int
InsufficientAmountException +getBalance(): double
+setBalance(balance: double): void
-account: Account +deposit(amount: double): void
-transactionAmount: double +withdraw(amount: double): void
Figure 13.9
609
NegativeAmountException and InsufficientAmountException
are subclasses of Exception that contain the account
information, transaction amount, and transaction type
for the failed transaction.
/**Return id*/
public int getId()
{
return id;
}
/**Return balance*/
public double getBalance()
{
return balance;
}
610
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
611
public class AccountApplet extends JApplet implements ActionListener
{
// Declare text fields
private JTextField jtfID, jtfBalance, jtfDeposit, jtfWithdraw;
// Register listener
jbtDeposit.addActionListener(this);
jbtWithdraw.addActionListener(this);
}
/**Handle ActionEvent*/
public void actionPerformed(ActionEvent evt)
{
String actionCommand = evt.getActionCommand();
if (evt.getSource() instanceof JButton)
if ("Deposit".equals(actionCommand))
{
try
{
double depositValue = (Double.valueOf(
jtfDeposit.getText().trim())).doubleValue();
account.deposit(depositValue);
refreshFields();
jlblStatus.setText("Transaction Processed");
}
catch (NegativeAmountException ex)
{
jlblStatus.setText("Negative Amount");
}
}
else if ("Withdraw".equals(actionCommand))
{
try
{
612
double withdrawValue = (Double.valueOf(
jtfWithdraw.getText().trim())).doubleValue();
account.withdraw(withdrawValue);
refreshFields();
jlblStatus.setText("Transaction Processed");
}
catch (NegativeAmountException ex)
{
jlblStatus.setText("Negative Amount");
}
catch (InsufficientFundException ex)
{
jlblStatus.setText("Insufficient Funds");
}
}
}
Example Review
613
amount, the message Negative Amount is displayed; for
insufficient funds, the message Insufficient Funds is
displayed.
Chapter Summary
Review Questions
614
13.5 What does the Java runtime system do when an
exception occurs?
statement4;
615
Answer the following questions:
try
{
System.out.println(
r1 + " + " + r2 + " = " + r1.add(r2));
System.out.println(
r1 + " - " + r2 + " = " + r1.subtract(r2));
System.out.println(
r1 + " * " + r2 + " = " + r1.multiply(r2));
System.out.println(
r1 + " + " + r2 + " = " + r1.add(r2));
}
}
}
616
System.out.println("The finally clause is executed");
}
}
}
617
13.16 What is displayed on the console when the following
program is run?
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("Welcome to Java");
int i = 0;
int y = 2/i;
System.out.println("Welcome to HTML");
}
catch (RuntimeException ex)
{
System.out.println("RuntimeException caught");
}
finally
{
System.out.println("Finally clause is executed");
}
int i = 0;
int y = 2/i;
}
catch (Exception ex)
{
System.out.println("Rational operation error ");
618
}
catch (RuntimeException ex)
{
System.out.println("Integer operation error");
}
}
}
int i = 0;
int y = 2/i;
System.out.println("Welcome to Java");
}
catch (RuntimeException ex)
{
System.out.println("Integer operation error");
}
catch (Exception ex)
{
System.out.println("Rational operation error");
}
}
}
int i = 0;
int y = 2/i;
System.out.println("Welcome to Java");
}
}
619
class Test
{
public static void main(String[] args)
{
try
{
method();
System.out.println("After the method call");
}
catch (RuntimeException ex)
{
System.out.println("Integer operation error");
}
catch (Exception ex)
{
System.out.println("Rational operation error");
}
}
int i = 0;
int y = 2/i;
System.out.println("Welcome to Java");
}
catch (RuntimeException ex)
{
System.out.println("Integer operation error");
}
catch (Exception ex)
{
System.out.println("Rational operation error");
}
}
}
int i = 0;
int y = 2/i;
System.out.println("Welcome to Java");
620
}
catch (RuntimeException ex)
{
System.out.println("Integer operation error");
}
catch (Exception ex)
{
System.out.println("Rational operation error");
throw ex;
}
}
}
Programming Exercises
Figure 13.10
621
11.2 Example 11.11, "Using Menus," is a GUI calculator.
Note that if Number 1 or Number 2 were a non-
numeric string, the program would display errors
on the console. Modify the program with an
exception handler to catch ArithmeticException
(i.e., divided by 0) and NumberFormatException
(i.e., input is not an integer) and display the
errors in a message dialog box, as shown in Figure
13.11.
Figure 13.11
rd
***Insert Figure 13.12 (Same as Figure 11.12 in the 3
Edition, p504)
Figure 13.12
622