Forums Register Login

exceptions

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
Create symphonies in seed and soil. For this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 649 times.
Similar Threads
code following the finally block.
Nested try/catch block
Exceptions Concepts
catch block does not compile
Exception handling: Statements after the finally block
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 18:36:12.