hi to everyone here
my doubt is about exception in java i´ve learned to use exception in Java using try catch....throw and throws and creating my own class. But i dont know where e why and when to every these things Because i thought in one way but now i knew other way the way i knew was create a class, extends from exception and put a code like this
I'm not sure if I understand your question... but I think your asking when your code should throw an exception vs. catching one?
IMHO if the class class containing you method is intend to be re-used I think you say that it throws exception x, but if you method is in a class containing the main method of your program( to be called by main) you definitely catch or preferably prevent the exception.
you should only say your method throws an exception if:
a. It is out of your hands... like a user choose a file that does exist( which could actually be be prevented by validating that the file exist... i'm sure there a better
b. it's is not called directly by main();
-just my humble opinion (I'm also a noobie)
Joined: Oct 13, 2005
Some of Campbell’s rules of exceptions:
1: Every rule about exceptions has lots of exceptions to it
2: Never throw an exception and catch it in the same method; that is simply am inefficient version of an if-else.
You should consider: what would you do if an exception occurs here? If you can say something definite, then catch the exception. If you say, “don’t know,” then you are probably better off re‑throwing it.
In your example, you are catching the same exception in the same method, so you ought to replace that with a simple if-else.
I shall remove
some of the
previous posts, because it is more difficult to read than ordinary text.
Joined: Oct 13, 2005
Branden Bobo wrote: . . . like a user choose a file that does exist( which could actually be be prevented by validating that the file exist... . . .
You can choose files which do exist, but are locked by another application, or read‑only. So you can suffer a FileNotFoundException (FNFE) even when the file definitely does exist. That is why FNFE is a checked Exception. You must handle it, and one way to handle it is give the user the opportunity of choosing a different file.
b. it's is not called directly by main(); . . .
Not sure I understand that bit.
Actually you ought not to call anything from the main method. It ought, if possible, to have one line and read something like this
subject: Understanding how to use exception in Java