Exception thrown by a catch{} Block

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        

Does DataInputStream.close() throw an exception?

Answer:

Yes, it throws an IOException when it encounters a problem.

Exception thrown by a catch{} Block

So there is a problem. The close() method inside the catch{} block throws an IOException which is not caught.

// Loop with problems

try
{
  while ( true )
    sum += instr.readInt();
}

catch ( EOFException eof )
{
  System.out.println( "The sum is: " + sum );
  instr.close(); <—— throws IOException 
}

catch ( IOException eof ) <—— this  catch is for the try{} block 
{                              not for the previous catch{} block

  System.out.println( "Problem reading input" );
  instr.close(); <—— throws IOException 
}

There are various ways to deal with this. One possibility is not to catch the exception that close() throws. Then the method header must be

public static void main(String[] args) throws IOException

QUESTION 10:

Can a try{}/catch{} be nested inside an outer try{} block?