Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Class Literals  RSS feed

 
Vineela Devi
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the problem with this code?
why is it throwing class not found Exception?
class ObjectTest
{
public static void main(String[] args)
{Class c = Class.forName("java.lang.String");
System.out.println(c);
}
}
Please explain the modification to be done for the code to compile well
 
himanshu patel
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vineela Devi Jakka:
what is the problem with this code?
why is it throwing class not found Exception?
class ObjectTest
{
public static void main(String[] args)
{Class c = Class.forName("java.lang.String");
System.out.println(c);
}
}
Please explain the modification to be done for the code to compile well

java.lang.ClassNotFoundException is of type "checked exceptions" and must be handled by program itself.So just add try/catch in your code.
Modified code :
class ObjectTest
{
public static void main(String[] args)
{
Class c = null;
try{
c = Class.forName("java.lang.String");
}catch(ClassNotFoundException e){}
System.out.println(c);
}
}
 
Jasmine kaur
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello ,
U are getting this exception at compile time because the method Class.forName() throws exception and it should be caught by using try and catch block or using throws clause in main method.well code should be like this and it will compile well.
class ObjectTest
{
public static void main(String[] args)
{
try{
Class c = Class.forName("java.lang.String");
}catch(Exception e){
System.out.println(e.getmessage());
}
System.out.println(c);
}
}
so now see it would run well.But please read exception handling in java and please free to ask further .
Thanks
jasmine
 
Vineela Devi
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi himanshu and jasmine,
Thanks for ur explanations.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!