1 // Exceptions.java
2 import java.util.Scanner;
3 import java.util.NoSuchElementException;
4
5 /** 6 * Exceptions zeigt den Umgang mit verschiedenen Ausnahmearten. 7 * Beispielprogramm zur Programmiertechnik 1, Teil 5. 8 * @author H.Drachenfels 9 * @version 10.12.2019 10 */
11 public final class Exceptions {
12 private Exceptions() {
13 // fatale Ausnahme werfen
14 throw new AssertionError("illegal class instantiation");
15 }
16
17 /** 18 * main ist der Startpunkt des Programms. 19 * @param args wird nicht verwendet. 20 */
21 public static void main(String[] args) {
22 try {
23 int n = InputOutput.readInt(); // evtl. InputException
24 n = sqrt(n); // evtl. IllegalArgumentException
25 InputOutput.print(n);
26 Exceptions e = new Exceptions(); // AssertionError
27 e.sqrt(n);
28 } catch (InputException x) {
29 String s = x.getMessage();
30 System.err.println(s); // Umgebungsfehler (Falscheingabe)
31 } catch (IllegalArgumentException x) {
32 x.printStackTrace(); // Programmierfehler besser nicht fangen
33 } catch (AssertionError e) {
34 e.printStackTrace(); // Programmierfehler besser nicht fangen
35 }
36 }
37
38 private static int sqrt(int n) {
39 if (n < 0) {
40 // ungepruefte Ausnahme mit Fehlermeldung werfen
41 throw new IllegalArgumentException(String.valueOf(n));
42 }
43 return (int) Math.sqrt(n);
44 }
45 }
46
47 class InputException extends Exception { // Klasse fuer gepruefte Ausnahmen
48 public InputException(String s) {
49 super("illegal input \"" + s + '\"');
50 }
51
52 public InputException(Throwable t) {
53 super(t);
54 }
55 }
56
57 final class InputOutput {
58 private InputOutput() {
59 // fatale Ausnahme werfen
60 throw new AssertionError("illegal class instantiation");
61 }
62
63 private static final Scanner IN = new Scanner(System.in);
64
65 public static int readInt() throws InputException {
66 try {
67 if (IN.hasNext() && !IN.hasNextInt()) {
68 // gepruefte Ausnahme mit Fehlermeldung werfen
69 throw new InputException(IN.next());
70 }
71 return IN.nextInt();
72 } catch (NoSuchElementException x) {
73 // gepruefte Ausnahme mit Ursache werfen
74 throw new InputException(x);
75 }
76 }
77
78 public static void print(int n) {
79 System.out.println(n);
80 }
81 }
82