简体   繁体   中英

exception never thrown while exceptional handling in java

I am pretty new to java programming and I am trying to learn exceptional handling in Java. In the following code I got an error:

unreported exception InvalidTestScore; must be caught or declared to be thrown throw new InvalidTestScore("Invalid Test Score");

I tried to figure out this problem but I couldn't, because it says it must be caught or declared, I gave the catch block which excepts the same exception argument which is thrown.

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);
    }
  }
}

You are doing

throw new InvalidTestScore("Invalid Test Score"); 

so you have to declare that your method is actually going to throw this exception

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

You must declare that your method may throw this exception:

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

This allows the compiler to force any method that calls your method to either catch this exception, or declare that it may throw it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM