• Post Reply Bookmark Topic Watch Topic
  • New Topic

exceptions  RSS feed

 
Nazma Panjwani
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I created this class StringTooLongException, which extends the exception class, then I created another class which basically takes in user input, and if string is too long (more than 20 characters), StringTooLongException is thrown.


here is the idea

so if exception is thrown program terminates.
Now, in another project, I am supposed to catch the exception and print the message.
so when I put the if-else statement under try block, and then there is a corresponding catch block..........it doesn't work......I only know how to catch exceptions that are
built into Java like Arithmetic exception.......
Anyways, compiler says "StringTooLongException" is already defined in main......what am I doing wrong??? How do I catch the exception???


Thanks
 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks like you're declaring two variables with the exact same name within the same scope, which is not allowed. It also looks funny that you're throwing the same exception that you're catching.
 
Nazma Panjwani
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks it works, I just changed the reference variable name. Actually, I am supposed to catch the same exception that I am throwing.......Thanks again
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After a "throw" the else is not required.

The point of an Exception is to tell a method that another method has not worked normally. Don't throw and catch an Exception in the same method. You can get the same effect much better with an if-else.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!