CPRE 486 Demonstration: Exception Handling

 

  1. We will write a Java program with main() and  fun(). Start with a hello world program:

import java.lang.*;

class HelloWorldApp {

    public static void  main(String [ ] args) {

       System.out.println("Hello World!"); //Display the string.

    }

}

 

  1. Add: import java.net.*;
  2. In fun(), declare and new a Socket for interacting with a given remote host at a given port. It doesn't matter if the host actually exists or not, because we will simply be using this statement as a vehicle for handling exceptions, not for actually connecting to a remote host. Syntax can conform to:
    Socket s=new Socket("class.ee.iastate.edu", 4444);

 

  1. Many I/O statements and other things are prone to error, so Java requires checking for problems. Find out more by trying to compile the code. The compiler tells you what kinds of exceptions you need to handle by giving error messages. To throw exceptions (down to the calling method, so in this case main() handles exceptions occurring in fun()) use this syntax:

           ...fun(...) throws ThisExeption {...}

Modify fun() so it throws the exception. This unmasks another possible kind of exception that could occur, so throw that one too. This will require you to import another library that contains the new exception.

 

  1. Modify the program so it try…catches one of the two kinds of exceptions that the Socket() constructor can cause, instead of throwing it.
  2. Also modify fun() so it throws any ArithmeticException that might occur. Java doesn't require you to deal with runtime exceptions like an ArithmeticException, but you can, as we are doing here.
  3. In main(), put a call to fun() in a try...catch construct that catches the appropriate exception thrown by fun(). In the catch clause, System.out.println() the exception.
  4. In fun(), add the following code: int n=9; n=n-n; n=n/n;. When run, this will cause a runtime situation (why?), which will be thrown by fun() and ultimately caught in main().  
  5. Compile and run, to make sure the arithmetic runtime exception is caught as expected.
  6. In main(), following the try...catch construct, print out "Exiting".
  7. Compile and run. Does it print out "Exiting"? Why or why not?  
  8. Comment out the catch clause that handles the ArithmeticException. Compile and run. Does it print out "Exiting" this time? Why or why not?
  9. Uncomment the commented catch. Add a finally{...} clause to your try...catch construct. The new clause should print out "Ending the program."
  10. Compile and run. Why does it print out "Ending the program."?
  11. Why does the program print both "Ending the program" and "Exiting"?