Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Custom Exceptions in Java
package customexceptions;
public class CustomExceptions {
public static void main(String[] args) throws NegativerWertException {
Rechner r = new Rechner();
try {
double wert1 = r.rechnung1(22.2);
System.out.println("wert1: " + wert1);
double wert2 = r.rechnung2(-5);
System.out.println("wert2: " + wert2);
} catch (NegativerWertException nw) {
System.out.println("Exception Abgefangen!");
System.out.println("Die Variable war: " + nw.getVariablenname());
}
}
}
package customexceptions;
public class NegativerWertException extends Exception {
private String variablenname = null;
public NegativerWertException() {
super("der Wert war negativ");
}
public NegativerWertException(String variablenname) {
super("der Wert der Variable "
+ variablenname
+ " war negativ");
this.variablenname = variablenname;
}
public String getVariablenname() {
return variablenname;
}
}
package customexceptions;
public class Rechner {
public double rechnung1(double x) {
return 2*x + 1;
}
public double rechnung2(double y) throws NegativerWertException {
if (y < 0) {
//throw new Exception("y < 0");
throw new NegativerWertException("y");
}
double z = Math.sqrt(y);
return y - z;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment