【发布时间】:2019-10-07 01:38:40
【问题描述】:
所以刚刚了解了 Java 中 try-catch 语句的基础知识,我仍然对语法中的一些差异感到有些困惑。
这是我试图分析和理解的代码。使用try 然后catch(Exception e) 与仅使用throws 或throw new 相比有什么区别?
据我了解,try 和catch 基本上是一种通过输出消息或传递给另一个方法来处理错误的方法。但是,我认为我停留在它的语法方面。
任何有建设性的 cmets 或简单的例子来阐明这个概念,以及我书中的示例代码发生了什么,我们将不胜感激。
/* 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;
}
}
【问题讨论】:
-
你读过this吗?
-
正确。然而,当你抛出一些东西,抓住它,然后将它传递给更多的方法,在 if-else 语句中使用它或者简单地说一些方法名称 + throws 这就是我的意思。
-
@Andy897 试试chat.stackexchange.com
-
@Andy897 我相信我们可以在聊天中进一步继续讨论。
-
@MarounMaroun 你的类比没有意义。