• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

exceptions

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic