aspose file tools*
The moose likes Beginning Java and the fly likes Why compile fine but run with exception? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why compile fine but run with exception?" Watch "Why compile fine but run with exception?" New topic
Author

Why compile fine but run with exception?

Zhixiong Pan
Ranch Hand

Joined: Jan 25, 2006
Posts: 239
Hi ranchers,
I have a class:
class Hotel{
String hotelName;
}

and in another class I produce Hotel objects:
class ConnectDB {
public static Hotel[] getHotel(){
}
}

and now is my question,

class Data{
private Hotel[] hotels = ConnectDB.getHotel();
}

in Data I have the main method,in main i have a sentence :

Data da = new Data();
System.out.print(da.hotels[8].hotelName);

so Data.java compile fine, but while i run it,there is exception of java.lang.StringIndexOutOfBoundsException .
Why?Can anyone help me ?


SCJP 1.4 SCJD
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

There's nothing here that would throw a StringIndexOutOfBoundsException; this is thrown by methods like String.charAt() that pick apart the characters of a String.

In any case, the compiler can only find so many problems; exceptions are due to problems that the compiler can't predict. It's perfectly normal for programs that compile fine to crash at runtime with an exception.


[Jess in Action][AskingGoodQuestions]
Zhixiong Pan
Ranch Hand

Joined: Jan 25, 2006
Posts: 239
Hi Ernest,
I want the result of System.out.print(da.hotels[8].hotelName) .But I failed to get it because of the exception.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

That's not the code that's throwing that exception. Can you show me the actual stack trace you get?
Zhixiong Pan
Ranch Hand

Joined: Jan 25, 2006
Posts: 239
Hi Ernest,
I have solved that problem by changing many codes. Thank you all the same.If I am more experienced in design class, problem like that will no longer happen.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
I suspect this actually belongs in the SCJD forum.


Tony Morris
Java Q&A (FAQ, Trivia)
 
 
subject: Why compile fine but run with exception?