So just got into the basics of try-catch statements in Java and I'm still a bit confused on some differences within the syntax.
Here is the code I'm trying to analyze and understand. What's the difference between using try
then catch(Exception e)
as compared to saying just throws
or throw new
?
From my understanding, a try
and catch
is basically a way to handle the error by outputting a message or passing to another method. However, I think I'm stuck on the syntax aspect of it.
Any constructive comments or simple examples clarifying this concept as well as whats going on with the sample code from my book would be appreciated.
/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
private double radius;
/** Construct an exception */
public InvalidRadiusException(double radius) {
super("Invalid radius " + radius);
this.radius = radius;
}
/** Return the radius */
public double getRadius() {
return radius;
}
}
public class CircleWithException {
/** The radius of the circle */
private double radius;
/** The number of the objects created */
private static int numberOfObjects = 0;
/** Construct a circle with radius 1 */
public CircleWithException() throws InvalidRadiusException {
this(1.0);
}
/** Construct a circle with a specified radius */
public CircleWithException(double newRadius) throws InvalidRadiusException {
setRadius(newRadius);
numberOfObjects++;
}
/** Return radius */
public double getRadius() {
return radius;
}
/** Set a new radius */
public void setRadius(double newRadius)
throws InvalidRadiusException {
if (newRadius >= 0)
radius = newRadius;
else
throw new InvalidRadiusException(newRadius);
}
/** Return numberOfObjects */
public static int getNumberOfObjects() {
return numberOfObjects;
}
/** Return the area of this circle */
public double findArea() {
return radius * radius * 3.14159;
}
}