Lösung Übung 17: Beispiel für Exception-Handling
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class DivisionsApp extends Applet {
Label prompt1, prompt2;
TextField input1, input2;
double result;
public void init() {
prompt1 = new Label("Geben Sie eine Zahl ein:");
input1 = new TextField( 10 );
prompt2 = new Label("Geben Sie eine Teiler ein " +
"drücken Sie Enter:");
input2 = new TextField( 10 );
input2.addActionListener( new FieldActionListener() );
add( prompt1 );
add( input1 );
add( prompt2 );
add( input2 );
}
class FieldActionListener implements ActionListener {
public void actionPerformed( ActionEvent e ) {
int number1, number2;
try {
number1 = Integer.parseInt( input1.getText() );
number2 = Integer.parseInt( input2.getText() );
}
catch( NumberFormatException exception ) {
showStatus( exception.toString() );
return;
}
finally {
input1.setText("");
input2.setText("");
Toolkit.getDefaultToolkit().beep();
}
try {
double result = quotient( number1, number2 );
showStatus( number1 + " / " + number2 + " = " +
Double.toString( result ) );
}
catch( DivideByZeroException exception ) {
showStatus( exception.toString() );
}
}
}
public double quotient( int numerator, int denominator )
throws DivideByZeroException {
if( denominator == 0 )
throw new DivideByZeroException();
return( (double)numerator/(double)denominator );
}
}
class DivideByZeroException extends Exception {
public DivideByZeroException() {
super("Versuch durch Null zu teilen gescheitert");
}
}
[Index]