Java Reference
In-Depth Information
}
System.out.println("Outside first try block in main()");
System.out.println("\nPress Enter to exit");
// This try block is just to pause the program before returning
try {
System.out.println("In second try block in main()");
System.in.read(); // Pauses waiting for input...
return;
} catch(IOException e) { // The read() method can throw exceptions
System.out.println("I/O exception caught in main()");
} finally { // This will always be executed
System.out.println("finally block for second try block in main()");
}
System.out.println("Code after second try block in main()");
}
Because the read() method for the object in (this object represents the standard input stream,
analogous to out ) can throw an I/O exception, it must itself be called in a try block and have an
associated catch block, unless we chose to add a throws clause to the header line of main() .
If you run the example it will produce the output:
First try block in main()entered
First try block in divide() entered
Code at end of first try block in divide()
finally block in divide()
result = 2
First try block in divide() entered
Arithmetic exception caught in divide()
finally block in divide()
Executing code after try block in divide()
result = 2
First try block in divide() entered
Index-out-of-bounds exception caught in divide
finally block in divide()
Executing code after try block in divide()
Index-out-of-bounds exception caught in main()
Outside first try block in main()
Press Enter to exit
In second try block in main()
finally block for second try block in main()
Search WWH ::




Custom Search