CPRE 486 Demonstration: Exception Handling
- 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.
}
}
- Add: import java.net.*;
- 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);
- 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.
- Modify
the program so it try…catches
one of the two kinds of exceptions that the Socket() constructor can cause, instead
of throwing it.
- 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.
- 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.
- 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().
- Compile
and run, to make sure the arithmetic runtime exception is caught as
expected.
- In
main(), following
the try...catch construct, print out "Exiting".
- Compile
and run. Does it print out "Exiting"? Why or why not?
- Comment
out the catch clause that handles the ArithmeticException. Compile and run. Does it print out
"Exiting" this time? Why or why not?
- Uncomment
the commented catch. Add a finally{...} clause
to your try...catch construct. The new clause should print out
"Ending the program."
- Compile
and run. Why does it print out "Ending the program."?
- Why
does the program print both "Ending the program" and
"Exiting"?