if else语句和try catchblock一起抛出错误

时间:2018-02-20 13:16:51

标签: java try-catch

//Program to Check the given Number is an odd or even number
import java.util.Scanner;

public class EvenOddNo { 

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number to check \"Even or Odd\" number");
        int k = sc.nextInt();
        String j =getNo(k);
        System.out.println(j);
        sc.close();
    }

    static public String getNo(int n) // Throwing an error *This method must   return a result of type String*
    {
        try {
            if(n%2==0) {
                return n+" is an Even number";
            }
            else
                return n+" is an Odd Number";
        }catch(ArithmeticException ae) {
            ae.printStackTrace();
          }
      }

}

1 个答案:

答案 0 :(得分:2)

如果您的try块抛出ArithmeticException会怎样?所以你错过了一个return语句。您必须在try-catch之后添加一个,最好是默认值。