Throw Exception

denis7788

Bekanntes Mitglied
Hallo,

ich habe eine eigene Exception geschrieben und versuche sie in einer Klasse zu werfen. Was ich nicht ganz nachvollziehen kann ist, warum
Java:
Exception e = new MyException();
throw e;
nicht funktioniert, aber folgendes schon:
Java:
throw new MyException();
Im oberen Fall erhalte ich "Unreported exception Exception; must be caught or declared to be thrown. Unten die Exception Klasse und die ausführende:
Java:
public class MyException extends Exception {

    public MyException() {
    }
    public MyException(String msg) {
        super(msg);
    }
  
    public String getMessage() {
        return "Das ist meine Exception!";
    }
}

Java:
public class Test {
  
    public Test() {
      
    }
  
    public static void testen(String str) throws MyException {
        if (str.equalsIgnoreCase("xyz")) {
          
            //Exception e = new MyException();
            throw ne MyException;
          
        }
      
        else {
            System.out.println("Alles ok ");
        }
    }
  
}
 
Zuletzt bearbeitet:
Im ersten Fall hast Du einen Cast von MyException zu Exception und dann wirfst Du die Exception.Der Compiler prüft ja nur statisch und daher verlangt er, dass in dem Fall ein throws Exception statt eines throws MyException angegeben wird.

Also kein cast auf Exception machen und gut ist es.
 

Zurück
Oben