Exceptions

Münchner

Aktives Mitglied
Servus Community, mein erster Thread!

Hallo, wir sollen mit Exceptions arbeiten.
Dabei sollen 2 Fehler abgefangen werden und folgelnde Konsolenausgabe erzeugt werden:
Code:
Exception bei Versuch 1
Exception bei Versuch 2
TEST
Fertig!

Der Code lautet folgendermaßen:
Code:
public class ExceptionTest {
public static void printUpperCase(String s) throws Exception1, Exception2 {
if (s == null)
throw new Exception1();
if (s.length() == 0)
throw new Exception2();
String upper = s.toUpperCase();
System.out.println(upper);
}
public static void printUpperCaseForArray(String[] array, int num) {

for (int i = 1; i <= num; i++) {
printUpperCase(array[i - 1]);
}
System.out.println("Fertig!");
}
public static void main(String[] args) {
String[] text = { null, "", "test" };
printUpperCaseForArray(text, 3);

Damit Exception1 und Exception2 funktionieren habe ich im gleichen Package 2 Klassen definiert:
Code:
public class Exception1 extends Exception {
}
und
Code:
public class Exception2 extends Exception1 {

}

mein Code lautet dann folgendermaßen.

Code:
public class Exception_Test    {
	public static void printUpperCase(String s) throws Exception1, Exception2 {
		if (s == null)
		throw new Exception1();
		if (s.length() == 0)
		throw new Exception2();
		String upper = s.toUpperCase();
		System.out.println(upper);
		}
		public static void printUpperCaseForArray(String[] array, int num) {
		
		for (int i = 1; i <= num; i++) {
		try {
			printUpperCase(array[i - 1]);
		} catch (Exception1 e) {
		
		System.out.println("Exception bei Versuch 1");
		
		}
		finally{
			System.out.println("text[1] war null!");
			System.out.println("text[2] war leer!");
		}
		}
		System.out.println("Fertig!");
		}
		public static void main(String[] args) {
		String[] text = { null, "", "test" };
		printUpperCaseForArray(text, 3);
		}
}
Das Programm wird korrekt ausgeführt, aber als Ausgabe erhalte ich folgendes:
Code:
Exception bei Versuch 1
Exception bei Versuch 1
TEST
Fertig!

Warum wird da zweimal die gleiche Zeile ausgegeben?
Vielen Dank,
Münchner
 
S

SlaterB

Gast
eine Exception2 ist auch eine Execption1, wegen Vererbung,
wenn du nur die allgemeinere Exception fängst, dann kommt dieses catch für beide dran,

eine Ausgabe "Exception bei Versuch 2" gibts in deinem Programm auch gar nicht,
was sollte denn bei Exception 2 ansonsten passieren?

du brauchst vielleicht Code a la

Java:
..
} catch (Exception2 e) {
   System.out.println("Exception bei Versuch 2");
} catch (Exception1 e) {
   System.out.println("Exception bei Versuch 1");
}
 

Münchner

Aktives Mitglied
Servus,
vielen Dank für deine schnelle Antwort.
Ich habs anfänglich auch mit 2 catch Blöcken gemacht, so wie du es vorgeschlagen hast.
Wir sollen aber nur einen catch Block verwenden. (und da scheiterts grad)
In dem hab ich dann das generellere catch.

Es macht ja keinen Unterschied, ob ich Exception 2 von 1 erben lassen, oder ob ich beide von der Oberklasse Exception erben lasse, oder?
Code:
public class Exception_Test    {
	public static void printUpperCase(String s) throws Exception1, Exception2 {
		if (s == null)
			throw new Exception1();
		if (s.length() == 0)
			throw new Exception2();
		String upper = s.toUpperCase();
		System.out.println(upper);
		}
		public static void printUpperCaseForArray(String[] array, int num) {
		
		for (int i = 1; i <= num; i++) {
		try {
			printUpperCase(array[i  -1]);
		} catch (Exception1 e) {	
			System.out.println("Exception bei Versuch 1");
		}
		catch(Exception2 e){
			System.out.println("Exception bei Versuch 2");
		}
		}
		System.out.println("Fertig!");
		}
		public static void main(String[] args) {
		String[] text = { null, "", "test" };
		printUpperCaseForArray(text, 3);
		}
}

so erscheint auch die korrekte Ausgabe, gibt es aber dennoch eine Möglichkeit mit dem generelleren auf den spezielleren zuzugreifen?
 
Zuletzt bearbeitet:

0din

Bekanntes Mitglied
Das ganze hier würde funktionieren wenn du zwei exception klassen gemacht hast die von exception erben ;) damit brauchst du nur ein mal die exception zu fangen (nur einmal nen catch bauen) un fängst doch alle möglichen fälle ab (exc.1 / exc.2 / sonstige exc.)

Java:
try
{
//bla..
}
catch(Exception e)
{
if(e instanceof Exception1) 
/*
*da ich mir grad net sicher bin wie das ganze genau mit der vererbung is eben der hinweis:
* wenns net tut bitte folgendes in die abfrage hinzufügen...
*  && !e instanceof Exception2
*/
{
//blabla
}
else
{
if(e instanceof Exception2)
{
//blablabla
}
else
{
e.printstacktrace();
}
}

}
 
Zuletzt bearbeitet:

Münchner

Aktives Mitglied
Servus, danke für die Antwort.
Ich denke mein Fehler war, den
Code:
try{}
Block nicht um das Schleifenkonstrukt herum gesetzt zu haben.
Folgendermaßen funktionierts:
Code:
public class Exception_Test {

	public static void printUpperCase(String s) throws Exception1, Exception2 {
		if (s == null)
			throw new Exception1();
		if (s.length() == 0)
			throw new Exception2();

		String upper = s.toUpperCase();
		System.out.println(upper);

	}
	public static void printUpperCaseForArray(String[] array, int num) {
		try{
		for (int i = 1; i <= num; i++) {
			printUpperCase(array[i - 1]);
			}}
			catch(Exception e){
				 System.out.println("Exception bei Versuch 1");
				 System.out.println("Exception bei Versuch 2");
			}		
		System.out.println("TEST");
		System.out.println("Fertig!");
	}
	public static void main(String[] args) {
		String[] text = { null, "", "test" };
		printUpperCaseForArray(text, 3);
	}
}
Die Ausgabe dazu lautet:
Code:
Exception bei Versuch 1
Exception bei Versuch 2
TEST
Fertig!
Was ich aber immer noch nicht verstehe, ist, warum vorher Exception bei Versuch 1 2Mal und nicht 3Mal gekommen ist???

Merci für Eure Antworten
 

mvitz

Top Contributor
Schöner wäre es übrigens so:

Java:
public class Exception_Test {
  public static void printUpperCase(String s) throws Exception1, Exception2 {
    if (s == null)
      throw new Exception1();
    if (s.length() == 0)
      throw new Exception2();

    String upper = s.toUpperCase();
    System.out.println(upper);
  }

  public static void printUpperCaseForArray(String[] array) {
    try{
      for (int i = 0; i < array.length; i++) {
        printUpperCase(array[i]);
      }
    } catch(Exception e) {
      System.out.println("Exception bei Versuch 1");
      System.out.println("Exception bei Versuch 2");
    }		
    System.out.println("TEST");
    System.out.println("Fertig!");
  }

  public static void main(String[] args) {
    String[] text = { null, "", "test" };
    printUpperCaseForArray(text);
  }
}

Du sparst dir die Übergabe der Anzahl der Element (ein Array weiß, wieviele Elemente es hat. Und die for-Schleife muss nicht noch i - 1 rechnen (macht es ein bisschen einfacher zu verstehen.)
 

eRaaaa

Top Contributor
das macht doch so imo garkeinen sinn?!
so kann man sich die zweite exception ja gleich sparen.

*doofFrag*: ist nicht eher sowas gemeint?
Java:
    public static void main(String[] args) {
	String[] text1 = { null, "Hallo", "Welt" };
	String[] text2 = { "", "Hallo", "Welt" };
	printUpperCaseForArray(text1);
	printUpperCaseForArray(text2);
	System.out.println("TEST");
	System.out.println("Fertig!");
    }

    public static void printUpperCase(String s) throws Exception1, Exception2 {
	if (s == null)
	    throw new Exception1();
	if (s.length() == 0)
	    throw new Exception2();

	String upper = s.toUpperCase();
	System.out.println(upper);
    }

    public static void printUpperCaseForArray(String[] array) {
	try {
	    for (int i = 0; i < array.length; i++) {
		printUpperCase(array[i]);
	    }
	} catch (Exception1 e1) {
	    System.out.println("Exception bei Versuch 1");
	} catch (Exception2 e2) {
	    System.out.println("Exception bei Versuch 2");
	}
    }

???:L
 

Oben