I was wondering if it was possible to write a method to throw an exception and have another method catch these exceptions.
For example,
public static void checkCircle() {
try {
checkPixel(a);
checkPixel(b);
checkPixel(c);
} catch (MyException e) {
System.out.println("not circle");
}
private static void checkPixel(anything) {
if (img.getRGB(xValue, yValue) != pOrigColour) {
throw new MyException();
}
}
class MyException extends Exception {
public MyException() {
}
public MyException(String msg) {
super(msg);
}
}
Thing is I want to the checkPixel method to throw a MyException, indicating that there is no circle, regardless of the results of the other calls.
Yes, it is possible. In your method declaration, you can add a
throwsclause, which indicates that your method might throw an exception.In your case, you should modify your method declaration like this:
You should note that exceptions should be used for… exceptional situations. Using them for simple error handling is highly unconventional, and adds unnecessary burden on users of your classes. In your case, you might want to add a
boolean hasCircleAtLocation ()method that would returntrueif there is a circle at the provided location.