java - 异常类不工作

标签 java exception io compiler-errors

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

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/

相关文章:

java - 如何终止 SwingWorker?

java - 准备语句时PreparedStatement资源泄漏

java - Throwables.propagate(e) 是否需要使用 throw 关键字?

java - 任何提高读取文件性能的方法,比缓冲读取器更好

java - 数学题: how to know if coordinate is in 'row' ?

java - 在Eclipse中添加分支

python - 使用 Python 'with' 语句时捕获异常

c# - 如何验证工厂方法?

c - 解释一下程序中fprintf()的奇怪行为,在文件中打印一些不寻常的字符

python - 如何使用 Python 从 Firestore 批量删除特定文档