When writing a program, you can anticipate on an exception by
using clauses with the keywords try
and catch
. In
the try-clause, you specify the statements that might throw an
exception, while in the catch-clause you tell what to do if
something goes wrong.
In the next applet, we adapt the above applet by catching the exceptions and sending them to an extra text area.
public boolean action (Event evt, Object arg) { if (evt.target == aField || evt.target == bField) { try { a = Integer.parseInt(aField.getText()); b = Integer.parseInt(bField.getText()); output = a/b; outputField.setText(String.valueOf(output)); exceptionArea.setText(""); } catch (Exception e) { outputField.setText(""); exceptionArea.setText(e.toString()); } } return true; }
try { ... } catch (ArithmeticException e) { exceptionArea.setText("You may not divide by zero!"); } catch (NumberFormatException e) { exceptionArea.setText("Please enter an integer."); }
finally
clause that
contains code that will be executed in any case, whether an
exception is generated or not.
try { ... } catch (...) { ... } finally { ... }