Created
June 5, 2013 15:22
-
-
Save haraldschilly/5714699 to your computer and use it in GitHub Desktop.
Custom Exceptions in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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