Ik probeer mijn eigen uitzonderingsklasse op de eenvoudigste manier te definiëren, en dit is wat ik krijg:
public class MyException extends Exception {}
public class Foo {
public bar() throws MyException {
throw new MyException("try again please");
}
}
Dit is wat de Java compiler zegt:
cannot find symbol: constructor MyException(java.lang.String)
Ik had het gevoel dat deze constructor geërfd moet worden van java.lang.Exception
, is het niet?
Nee, je erft"niet-default constructors niet, je moet degene die een String neemt definiëren in je klasse. Typisch gebruik je super(message)
in je constructor om je ouder constructor aan te roepen. Bijvoorbeeld, zoals dit:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
Een typische aangepaste uitzondering die ik zou definiëren is zoiets als dit:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable throwable) {
super(message, throwable);
}
}
Ik maak zelfs een sjabloon met behulp van Eclipse zodat ik'niet alles steeds opnieuw hoef te schrijven.