R.A.M. wrote On 01/02/07 09:32,:
Hello,
I have started learning Java. In a tutorial I found such example
(pseudocode):
method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
Could you tell me please why method2 needs "throws exception"? Do the
programmer need to check what exceptions are generated by all called
methods?
Yes, or pretty nearly so. There are "checked exceptions"
and "unchecked exceptions," and you are allowed to ignore the
latter. For checked exceptions, though, the rules are:
- If a method can cause a checked exception to be thrown,
the method must say "throws WhateverException" to warn
its callers of the possibility.
- If you call a method that can throw a checked exception,
you must arrange to do something about the exception if
one is in fact thrown. The compiler will complain if you
call such a method and don't make arrangements.
- One thing you can do with an exception is catch it, the
way method1 does. If you catch it, the compiler trusts
that you have done something appropriate to respond to
the exceptional circumstance.
- The other thing you can do is pass the exception along
to your caller; this is what method3 does with exceptions
thrown by readFile. If you do this, you must announce
the fact with a "throws WhateverException" of your own
to warn your callers that an exception might be thrown.
method3 calls readFile, and since readFile can (presumably)
throw an exception, method3 must do something about it. In the
sample, method3 decides to pass the exception along to its own
caller, which is why method3 announces "throws exception."
method2 calls method3, which can cause an exception to be
thrown. True, method3 won't throw the exception itself: it
will just pass along whatever readFile throws. But method2
doesn't really care: All it knows is that calling method3 can
produce an exception, so method2 must do something about it.
In the sample, method2 decides to pass the exception along
rather than catching it, so method2 "throws exception" to warn
its callers.
method1 calls method2, which can cause an exception to be
thrown. This time, though, method1 decides to handle the
problem locally: It catches the thrown exception and executes
doErrorProcessing code. Since the exception is caught inside
method1, it never gets out to method1's callers -- and that is
why method1 does *not* need to announce "throws exception."