我被要求编写一个程序来使用try和catch处理异常。虽然,当我运行它时,它不会反映我的异常代码,因为应该打印“无效名称”。有人可以指出原因吗?如果有人纠正了我的代码,也将非常欢迎!谢谢。

我需要在以下条件下编写程序:

导入javax.naming.InvalidNameException。
写一个方法public void printName(String name)throws InvalidNameException
如果name没有空格,则该方法应引发InvalidNameException。
编写驱动程序进行测试。

===============Code result=============
Enter your name: James Dean
First name: James
Last name: Dean
Enter your name: Brian Smith
First name: Brian
Last name: Smith
Enter your name: RuthKnight
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at Name.printName(Name.java:33)
    at NameApp.main(NameApp.java:17)




==================Method============================
import javax.naming.InvalidNameException;

public class Name{

   public void printName(String name) throws InvalidNameException{

       String [] nameSplit = name.split(" ");
       String first = nameSplit[0];
       String last = nameSplit[1];

       System.out.println("First name: "+first);
       System.out.println("Last name: "+last);
   }

}




======================Driver========================
import java.util.Scanner;
import javax.naming.InvalidNameException;


public class NameApp{

   public static void main(String[] args) {

      Name aa = new Name();
      Scanner console = new Scanner(System.in);
      try {
         boolean keepRunning= true;

         while(keepRunning){
            System.out.print("Enter your name: ");
            String in = console.nextLine();
            aa.printName(in);
         }
      }
      catch(InvalidNameException e){
         System.out.println("invalid name");
      }
   }

}

最佳答案

我建议在Name类中捕获异常,然后在throw InvalidNameException中捕获异常,如下所示:

public void printName(String name) throws InvalidNameException {
    try {
        String[] nameSplit = name.split(" ");
        String first = nameSplit[0];
        String last = nameSplit[1];

        System.out.println("First name: " + first);
        System.out.println("Last name: " + last);
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new InvalidNameException("Missing space in: " + name);
    }
}


更新

运行此代码:

import javax.naming.InvalidNameException;
public class NameApp{
   public static void main(String[] args) {
      Name aa = new Name();
      try {
            System.out.print("Enter your name: ");
            String in = "George Den";
            aa.printName(in);
            in = "George";
            aa.printName(in);
      }
      catch(InvalidNameException e){
         System.out.println(e.toString());
      }
   }
}

import javax.naming.InvalidNameException;
public class Name {
    public void printName(String name) throws InvalidNameException {
        try {
            String[] nameSplit = name.split(" ");
            String first = nameSplit[0];
            String last = nameSplit[1];
            System.out.println("First name: " + first);
            System.out.println("Last name: " + last);
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new InvalidNameException("Missing space in: " + name);
        }
    }
}


将打印此:


  输入您的姓名:名字:George姓:Den
  
  javax.naming.InvalidNameException:缺少空格:George


更新2

考虑@robjohncox的建议。不应按原样使用此代码,因为javax.naming.InvalidNameException仅应在特定情况下抛出,例如LDAP查找和通常针对目录的操作。

最适合您的是对Exception Object进行子类化并创建自己的异常类型(另请参见以下How can I write custom Exceptions?):

public class MyCustomNamingException extends Exception {
    public MyCustomNamingException(){
    }
    public MyCustomNamingException(String message){
        super(message);
    }
}


然后像以前使用MyCustomNamingException所示在代码中使用此InvalidNameException

09-26 17:13