gpt4 book ai didi

java - 异常类不工作

转载 作者:行者123 更新时间:2023-12-02 03:13:20 26 4
gpt4 key购买 nike

我有一个程序试图抛出某个异常。我在这里创建了一个自定义异常类:

import java.io.*;

public class ShapeException extends Exception
{
public ShapeException(String message)
{
super(message);
}
}

这是我尝试实现异常的类:

import java.io.*;

public class Circle
{
private double radius;

public Circle(double inRadius )
{
if(inRadius < 0.0)
{
throw new ShapeException("Shape Exception Occurred...");
}
else
{
radius = inRadius;
}
}

public double getRadius()
{
return radius;
}

public void setRadius(double newRadius)
{
if(newRadius < 0.0)
{
throw new ShapeException("Shape Exception Occurred...");
}
else
{
radius = newRadius;
}
}

public double area()
{
return Math.PI * radius * radius;
}

public void stretchBy(double factor )
{
if(factor < 0.0)
{
throw new ShapeException("Shape Exception Occurred...");
}
else
{
radius = radius * factor;
}
}

public String toString()
{
return "Circle Radius: " + radius;
}
}

但是,这不会编译并给出错误,告诉我必须捕获或声明抛出我的形状异常错误。我究竟做错了什么?这不是声明了吗?

最佳答案

在java中,每当你抛出一个受检查的异常时,你需要在方法签名中使用throws关键字声明它。下面是没有任何编译错误的代码片段,因为每个方法在抛出 ShapeException 的地方都有 throws 声明。

public class Circle {
private double radius;

public Circle(double inRadius) throws ShapeException {
if(inRadius < 0.0) {
throw new ShapeException("Shape Exception Occurred...");
} else {
radius = inRadius;
}
}

public double getRadius() {
return radius;
}

public void setRadius(double newRadius) throws ShapeException {
if(newRadius < 0.0) {
throw new ShapeException("Shape Exception Occurred...");
} else {
radius = newRadius;
}
}

public double area() {
return Math.PI * radius * radius;
}

public void stretchBy(double factor) throws ShapeException {
if(factor < 0.0) {
throw new ShapeException("Shape Exception Occurred...");
} else {
radius = radius * factor;
}
}

@Override
public String toString() {
return "Circle Radius: " + radius;
}
}

关于java - 异常类不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40730617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com