【问题标题】:exception never thrown while exceptional handling in java在java中进行异常处理时从不抛出异常
【发布时间】:2019-07-19 16:34:56
【问题描述】:

我对 Java 编程很陌生,我正在尝试学习 Java 中的异常处理。在下面的代码中我得到了一个错误:

未报告的异常 InvalidTestScore;必须被抓住或宣布被扔掉 throw new InvalidTestScore("无效的测试分数");

我试图解决这个问题,但我不能,因为它说它必须被捕获或声明,我给出了 catch 块,除了抛出的相同异常参数。

import java.io.*;
import java.util.*;

class InvalidTestScore extends Exception {
public InvalidTestScore(String msg) {
  super(msg);
}

public class TestClass {

  public static void inTestScore(int[] arr) {
    int sum = 0, flag = 0;
    for (int i = 0; i < arr.length; i++) {
      if (arr[i] < 0 || arr[i] > 100) {
        flag = 1;
        break;
      } else {
        sum += arr[i];
      }
    }

    if (flag == 1) {
      throw new InvalidTestScore("Invalid Test Score");
    } else {
      System.out.println(sum / arr.length);
    }
  }

  public static void main(String[] args) {
    int n;
    Scanner input = new Scanner(System.in);
    n = input.nextInt();
    int[] arr = new int[n];
    for (int i = 0; i < n; i++) {
      arr[i] = input.nextInt();
    }

    try {
      inTestScore(arr);
    } catch (InvalidTestScore e) {
      System.out.println(e);
    }
  }
}

【问题讨论】:

  • 仅仅因为“可能”抛出异常,并不意味着它会。例如,如果您提供了无效的输入参数,方法 x 将抛出异常,但传递了一百万次有效参数,则不会发生任何异常情况。这并不意味着 JVM 不希望你“处理”它发生的情况

标签: java exception try-catch


【解决方案1】:

你在做

throw new InvalidTestScore("Invalid Test Score"); 

所以你必须声明你的方法实际上会抛出这个异常

public static void inTestScore(int[] arr) throws InvalidTestScore

【讨论】:

    【解决方案2】:

    你必须声明你的方法可能会抛出这个异常:

    public static void inTestScore(int[] arr) throws InvalidTestScore {
        ...
    }
    

    这允许编译器强制任何调用你的方法的方法要么捕获这个异常,要么声明它可以抛出它。

    【讨论】:

      猜你喜欢
      • 2013-07-24
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2013-05-24
      相关资源
      最近更新 更多