2

I am asked to write a piece of program to handle exception using try and catch. Although, when I ran it, it would not have reflected my exception codes as "invalid name" should have printed. Can anybody point the reason out? If someone corrects my code would be big welcome as well! Thanks.

I need write a program under the following conditions :

import javax.naming.InvalidNameException. Write a method public void printName(String name) throws InvalidNameException If name has no white space the method should throw an InvalidNameException. Write a driver to test.

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

}
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
Evan S
  • 191
  • 1
  • 5
  • 12
  • 2
    InvalidNameException isn't thrown anywhere here, and should not be used at all - this exception is designed for use by the javax.naming package and should not be repurposed. – robjohncox Jul 03 '13 at 07:31

6 Answers6

2

I would suggest to catch the Exception in the Name class and then throw the InvalidNameException like this:

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

UPDATE

Running this code:

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

Will print this:

Enter your name: First name: George Last name: Den

javax.naming.InvalidNameException: Missing space in: George

UPDATE 2

Take into account @robjohncox advice. This code shouldn't be used as is because the javax.naming.InvalidNameException should be thrown only at specific cases such as LDAP lookups and generally directory specific operations.

What should be best for you is to sub-class Exception Object and create your own kind of exception (see also this How can I write custom Exceptions? ):

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

And then use this MyCustomNamingException in your code as was previously illustrated using the InvalidNameException

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
  • It led this result.....error: unreported exception InvalidNameException; must be caught or declared to be thrown aa.printName(in); – Evan S Jul 03 '13 at 08:14
  • Thank you so much for your update! I ran them and they worked the way I wanted. Thanks for your effort. I am novice to Java. So I need full codes to understand sometimes. I will take some time to memorize them tonight :-) – Evan S Jul 03 '13 at 09:26
1

Simply do something like this:

if (name.contains(" ")) {

} else {

throw new InvalidNameException ("Name does not contain the space");
}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

The behavior is as expected, the exception is triggered by the line

String last = nameSplit[1]

because the result of "RuthKnight".split(" ") results in an array with a single element, and therefore it has no element at position 1 (causing the ArrayIndexOutOfBoundsException to be thrown).

The exception type javax.naming.InvalidNameException isn't thrown anywhere in your code, and you shouldn't really use it as this exception is designed for use by the Java naming services code in javax.naming.

You should modify your code something like this:

String in = console.nextLine();
if (in.contains(" ") {
     aa.printName(in);
}
else {
    System.out.println("invalid name");
}
robjohncox
  • 3,639
  • 3
  • 25
  • 51
  • Hi Robjohncox! I would be happy as well if I could write codes like you wrote :-) But it is given task so no choice but to use javax.naming.InvalidNameException. Thanks for the explanation on ArrayIndexOutOfBoundsException. – Evan S Jul 03 '13 at 07:52
  • No choice but to use InvalidNameException? That is unusual. Perhaps you should rebel against the task and explain why it shouldn't be used :) – robjohncox Jul 03 '13 at 07:53
  • Rebel? HAHAHA That's cool though! Since I have to deal with it, no hesitate to share your input if you know about it. It would be helpful. Thanks :-) – Evan S Jul 03 '13 at 08:03
0

you need to check that entered name is splitable or not if not then you do not have value name[1] that is why it is throwing exception

shreyansh jogi
  • 2,082
  • 12
  • 20
0

i this scenario you entered named as RuthKnighthe name string contain only single string.

instead of this

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

put if

if( name.contains(" "))
 {
  String [] nameSplit = name.split(" ");
  String first = nameSplit[0];
  String last = nameSplit[1];
 }
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
0
   String[] nameSplit = name.split(" +", 2);
   if (nameSplit.length < 2) {
       throw new InvalidNameException ("Missing space in: " + name);
   }

The optional parameter 2 of split indicates the maximum number of splits. Try "José del Rey".

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138