/** * @author monika heiner * @version 1.01 * @date 04.04.2002 * @class ExceptionDemo4 */ import java.util.Scanner; public class ExceptionDemo4 { // thrown, but not caught exceptions must be reported in a "throws clause" // errors and RuntimeExceptions do not need to be listed static void operationEvaluation(int op, int a, int b) throws DivideByZeroException, OpException { switch (op) { case 1 : System.out.println(" result: " + (a + b)); break; case 2 : System.out.println(" result: " + (a - b)); break; case 3 : System.out.println(" result: " + (a * b)); break; case 4 : if (b == 0) { throw new DivideByZeroException(); } else { System.out.println(" result: " + (a / b)); } // if break; case 5 : if (b == 0) { throw new DivideByZeroException(); } else { double realB = b; System.out.println("result: " + (a / realB)); } // if break; case 6 : System.exit(0); default : throw new OpException(); } // switch } // operationEvaluation public static void main(String[] argv) { int a, b, op; System.out.println("willkommen zur wiederholung der grundrechenarten"); op = getInt("Operationsauswahl: \n" + " 1 -->> add\n" + " 2 -->> sub\n" + " 3 -->> mul\n" + " 4 -->> div\n" + " 5 -->> real div\n" + " 6 -->> exit\n" + "Operation: "); while (true) { a = getInt(" a: "); b = getInt(" b: "); // OpException must be caught or declared to be thrown try { operationEvaluation(op, a, b); } // try catch (OpException e) { System.out.println(e.getMessage()); } catch (DivideByZeroException e) { System.out.println( "operation skipped, because division by zero not defined"); // System.out.println(e.getMessage()); } catch (Exception e) { System.out.println("operation skipped, because "); } finally { // optional, generally // required if no catch block } // catch op = getInt("next Operation: "); } // while } // main // Vereinfachung der Eingabe static int getInt(String message) { Scanner in = new Scanner(System.in); System.out.print(message); return in.nextInt(); } // getInt } // ExceptionDemo4 //------------------------ cut here into separate files -------------------------------- // definition of a 'throwable object' // -> any class derived from class Throwable, e.g. Exception or Error class DivideByZeroException extends ArithmeticException { public DivideByZeroException() { super("division by zero attempted"); // string is passed to system's exception system // so that it is available for printing } public DivideByZeroException(String s) { super(s); } } // class DivideByZeroException //------------------------ cut here into separate files -------------------------------- class OpException extends Exception { public OpException() { super("wrong operation code"); } } // class OpException