Ayush
Ayush

Reputation: 49

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

Upvotes: 1

Views: 110

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44834

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

Upvotes: 4

Eran
Eran

Reputation: 393801

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.

Upvotes: 1

Related Questions