↑
Main Page
Handling Java exceptions
This example presents the user with a text box where a new message can be entered. When the user
clicks the Set Message button, it calls the
changeAppletMessage()
function, which gets a reference to
the applet and retrieves the text from the text box. Then, the function calls the applet’s
setMessage()
method, passing in the entered text. The message displayed in the applet changes from
“Hello
World!”
to whatever the user enters (sometimes this happens quickly, sometimes slowly).
Type conversion
Although JavaScript-to-Java communication is a powerful tool for developers, it is not without its issues.
In the previous example, a string was passed from JavaScript to a Java method without issue. That’s
because the JavaScript
String
object maps directly to the Java
String
object. The same is true for any
primitive value in JavaScript because they all have equivalent primitive types in Java. You can run into
trouble when trying to pass objects into a Java method because no equivalent class exists. For this rea-
son, it’s always best that any method you create for use with JavaScript accept only primitive values.
Handling Java exceptions
Exceptions are much more common in Java than in JavaScript, so you must be aware when they could
possibly occur. When accessing an applet method that could cause an error, you can prepare by wrap-
ping the call in
try..catch
statement. Yes, the JavaScript
try..catch
statement catches exceptions
thrown by an applet.
Suppose you change the
ExampleApplet
to throw an error if
setMessage()
is passed a zero-length
string, such as:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.HeadlessException;
public class ExampleApplet2 extends Applet {
private String message = “Hello World!”;
public ExampleApplet2() throws HeadlessException {
super();
}
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
public void setMessage(String message) throws Exception {
if (message.length()== 0) {
throw new Exception(“Message must have at least one character.”);
}
this.message = message;
repaint();
}
}
547
Interacting with Plugins
21_579088 ch18.qxd 3/28/05 11:43 AM Page 547
Free JavaScript Editor
Ajax Editor
©
→