Java Reference
In-Depth Information
1
// Fig. 11.5: UsingExceptions.java
2
// try...catch...finally exception handling mechanism.
3
4
public class UsingExceptions
5
{
6
public static void main(String[] args)
7
{
8
try
9
{
10
throwException();
11
}
12
catch (Exception exception) // exception thrown by throwException
13
{
14
System.err.println( "Exception handled in main" );
15
}
16
17
doesNotThrowException();
18
}
19
20
// demonstrate try...catch...finally
21
public static void throwException() throws Exception
22
{
23
try // throw an exception and immediately catch it
24
{
25
System.out.println( "Method throwException" );
26
throw new Exception(); // generate exception
27
}
28
catch (Exception exception) // catch exception thrown in try
29
{
30
System.err.println(
31
"Exception handled in method throwException" );
32
throw exception; // rethrow for further processing
33
34
// code here would not be reached; would cause compilation errors
35
36
}
37
finally // executes regardless of what occurs in try...catch
{
System.err.println( "Finally executed in throwException") ;
}
38
39
40
41
42
// code here would not be reached; would cause compilation errors
43
44
}
45
46
// demonstrate finally when no exception occurs
47
public static void doesNotThrowException()
48
{
49
try // try block does not throw an exception
50
{
51
System.out.println( "Method doesNotThrowException" );
52
}
Fig. 11.5 | try catch finally exception-handling mechanism. (Part 1 of 2.)
Search WWH ::




Custom Search