今天自定义了一个异常类,继承Exception就会报错,但是继承Throwable就没有问题啦!想了半天也不知道问题所在,找度娘也无解,不能是JDK的问题吧,我装的是新版本1.7的。我把代码粘在下面,望知道问题所在的大神们不吝赐教!

 

package cn.com.hrbust.Test;

public class Exception {
 public static void main(String[]args) {
  B b = new B();
  try {
   b.f(100);
   b.f(-9);
  } catch (IsMyException e) {
   System.out.println(e.getMessage());
  }
 }
}

class IsMyException extends Throwable { //如果把Throwable换成Exception就会出现错误
 String message;
 IsMyException(int n) {
  message = n+"不是正数";
 }
 public String getMessage() {
  return message;
 }
}
class B{
 public void f(int n) throws IsMyException {
  if(n<0) {
   IsMyException e = new IsMyException(n);
   throw(e);
  }
  double number = Math.sqrt(n);
  System.out.println(n+"的平方根:"+number);
 }
}

相关文章:

  • 2021-06-13
  • 2021-08-24
  • 2021-12-15
  • 2022-01-09
  • 2021-07-16
  • 2022-02-24
  • 2021-08-04
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-22
  • 2021-11-12
  • 2022-12-23
  • 2022-02-07
  • 2021-06-30
  • 2021-10-26
相关资源
相似解决方案