/** * @author monika heiner * @version 1.01 * @date 14.05.2012 * @class ExceptionDemo3 */ // Standard runtime exceptions werden abgefangen und behandelt // zusaetzlicher Einsatz von nutzer-definierten Exceptions import java.util.Scanner; public class ExceptionDemo3 { public static void main(String[] argv) { int a, b, op; double realB; 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 ((op > 0) && (op < 6)) { a = getInt(" a: "); b = getInt(" b: "); try { 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("zero division in real div op"); } else { realB = b; System.out.println("result: " + (a / realB)); } // if break; } // switch } // try catch (DivideByZeroException e) { System.out.println(e + " -> operation skipped"); } // catch catch (Exception e) { System.out.println("operation skipped, because "); } // catch // finally { } op = getInt("next Operation: "); } // while System.out.println("auf wiedersehen!"); } // main // Vereinfachung der Eingabe static int getInt(String message) { Scanner in = new Scanner(System.in); System.out.print(message); return in.nextInt(); } // getInt } // ExceptionDemo3 //------------------------ 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