Slide 14
Slide 14 text
class OperatorException extends RuntimeException {
public OperatorException(String msg) { super(msg); }
}
class Main {
public static void main(String [] args) {
try {
String operator = parseOperator("f");
} catch(OperatorException e) {
// Must be +, -, or /
System.out.println(e.getMessage());
}
}
public static String parseOperator(String isThisOperator) throws OperatorException {
String [] operators = {"+", "-", "/"};
boolean success = false;
for(String operator: operators) {
if(operator.equals(isThisOperator)) {
success = true;
}
}
if(success) {
return isThisOperator;
} else {
OperatorException ex = new OperatorException("Must be +, -, or /");
throw ex;
}
}
}
To give additional information
about the Exception, you can
use message