Nested try{} Blocks

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Yes.

Nested try{} Blocks

A method can catch some exceptions and not others. Since problems with closing a file are rare, not catching this one would be tolerable. But a commercial-grade program should take care of everything. Here is one way:

try
{
  // other stuff goes here


  try
  {
    while ( true )
      sum += instr.readInt();
  }
  catch ( EOFException eof )
  {
    System.out.println( "The sum is: " + sum );
    instr.close(); 
  }
  catch ( IOException iox )
  {
    System.out.println( "Problems reading " + fileName );
    instr.close(); 
  }

}

catch ( IOException iox )
{
  System.out.println( "IO Problems with" + fileName );
}

The logic dealing with reading input and catching end of file is put inside a try{} block that is concerned with errors. This is messy, but IO programming always is.

This example is probably more complicated than you would normally write. It can be slightly simplified by using a finally{} block inside the nested try{} block.

QUESTION 11:

If the readInt() throws an IOException, where will it be caught?