Java Reference
In-Depth Information
Example 3.20
Catching different kinds of exceptions
try {
for (i = 0; i < max; i++) {
someobj.methodB(param1, i);
} // next i
} catch (SpecialException sp) {
System.out.println(sp.whatWentWrong());
} catch (AlternateException alt) {
alt.attemptRepair(param1);
} catch (Exception e) {
// do the error handling here:
System.out.println(e.toString());
e.printStackTrace();
}
// continues execution here after any catch
Example 3.21
Output from
printStackTrace()
java.lang.Exception: Error in the fraberstam.
at InnerMost.doOtherStuff(InnerMost.java:6)
at MidModule.doStuff(MidModule.java:7)
at AnotherClass.doSomething(AnotherClass.java:11)
at ExceptExample.main(ExceptExample.java:14)
AnotherClass
, which itself had been called from line14 in the
ExceptExample
class'
main()
method.
We want to mention one more piece of syntax for the
try/catch
block.
Since execution may never get to all of the statements in a
try
block (the excep-
tion may make it jump out to a
catch
block), there is a need, sometimes,
for some statements to be executed regardless of whether all the
try
code
completed successfully. (One example might be the need to close an I/O con-
nection.) For this we can add a
finally
clause after the last
catch
block. The
code in the
finally
block will be executed (only once) after the
try
or after
the
catch
—even if the path of execution is about to leave because of throwing
an exception (Example 3.22).