OH-slides in powerpoint

Download Report

Transcript OH-slides in powerpoint

9. Exceptions
An exception occurs when our code asks the
JVM to perform the technically impossible
and unanticipated (by the compiler)!
Under these circumstances, the JVM
generates an exception. If we don’t catch the
exception, the program crashes!
• User Input Errors:
– connect to a URL which is incorrect
– network exception
• Device Errors:
– printer is off/ out of paper
– Network is down
• Physical limitations:
– Disks run out of memory,
– quotas fill up,
– an infinite recursion causes a stack overflow.
• Code errors:
–
–
–
–
divide by zero,
array out of bound,
integer overflow,
access a null pointer.
Programs only crash if an exception goes
untrapped, i.e. is not handled by the
program.
1. When an exception occurs, Java allows a
method to terminate abnormally
2. It throws an object that encapsulates error
information
3. It does not return a value
4. It exits immediately
5. Execution does not resume at the point of
method call
6. JVM searches for an exception handler
7. If none is found, the program crashes.
9.1. Exception Handling
All exception handling has the same goals:
1. Anticipate the error by the user/system
2. Return the program to a safe state that
enables the user to execute other
commands
3. Inform the user of the error’s cause
4. Allow the user to save work and terminate
the program gracefully.
Throwable
Error
The Java
Exception
Hierarchy
Exception
IO
Exception
Runtime
Exception
• Error hierarchy describes internal errors
and resource exhaustion.
• Don’t throw an object of this type!
• Notify the user and try to terminate
gracefully
• Relatively rare
• Mostly beyond programmers control
•
•
•
•
IOException
Trying to read past the end of file
Trying to open a malformed URL
Trying to find a class object for a string that
does not denote an existing class
• Methods tell Java their return type, but also
what can go wrong
Public String readLine() throws IOException
• RuntimeException caused by
programming error
• “If it’s a RuntimeException it’s your
fault!”
• Bad cast
• Out-of-bounds array access
• Null pointer access
• Can all be protected against by code tests.
4 Ways to throw an Exception
1. Calling a method that throws a checked
exception, e.g. readLine
2. Code detects an error and generates checked
exception with throw statement
3. Programming error e.g. a[-1] =0; generates
an unchecked exception
ArrayIndexOutOfBoundsException
4. JVM or runtime library internal error
9.1.1. Caution!!
• If you override a method from a superclass
in your subclass you cannot throw more
exceptions than the superclass method. But
you can throw less
• Reason – if you don’t catch the exception
the superclass can’t catch the exception –
and then what??
9.2. How to Throw an
Exception
•
•
•
1.
2.
3.
4.
Suppose we are writing a file reader …
Header promises 1024 bytes …
But ... end of file after 600 bytes!
Decide what kind of exception to throw
Look up Java exception hierarchy
Subclass of IOException seems natural
Settle on EOFException
• API Description “Signals that an EOF has
been reached unexpectedly during input”
String myReadData(BufferedReader in)
throws EOFException
{
…
if (ch = -1) // EOF encountered
{
if (n < len) throw EOFException();
}
return s
}
•
If an existing exception class works for
you then throwing is easy
1. Find an appropriate class
2. Make an object of that class
3. Throw it
•
Also
EOFException e = new
EOFException();
throw e;
9.3. Error Messages
Often have a second constructor with a String
parameter.
String message =
“Content-length: “ + len “ + “received” + n;
throw new EOFException(message);
9.4. Creating your Own
Exception Classes
• You may not find a good existing exception
class
• Can subclass Exception to create your own
• Give a default constructor and a constructor
that takes a message
class MyFileException extends IOException
{
public MyFileException ( ) { … }
public MyFileException(String message)
{
super(message);
}
}
String myReadData(BufferedReader in)
throws MyFileException
{
…
if (ch = -1) // EOF encountered
{
if (n < len) throw
new MyFileException(“Help!”);
}
return s
}
9.5. Catching Exceptions
• “What goes up must come down”
• Catching exceptions is a bit trickier
• Something must catch the exception (see
9.1.1)
• An uncaught exception will terminate the
program …
• … print the exception type to screen …
• … print the stack trace.
9.6. try/catch block
try
{
mycode …
}
catch (ExceptionType e)
{
handler for just this exception type …
}
• If any code inside try block throws an
exception of type specified in catch clause
program skips remainder of code in try block
• Then program executes handler code inside
catch block
• If no code in try block throws an exception
of specified type then catch block never
executes.
• If another exception is thrown (not a subclass
of catch exception type) this must be caught
separately
public void read(BufferedReader reader)
{
try {
…
String line = reader.readLine();
…
}
catch IOException exception)
{
exception.printStackTrace();
}
}
• Can also just throw an exception without
catching it.
public void read(BufferedReader reader) throws
IOException
{
…
String line = reader.readLine();
…
}
• Lets the method caller deal with it!
• So which is best???
Rule: catch those exceptions you know how
to handle and propagate those you do not.
• Rule Exception: overriding a superclass
method that throws no exceptions. Then you
must catch each checked exception.
9.7. Catching Multiple
Exceptions
try { mycode }
catch (BadURLException e1) { … }
catch (UnknownHostException e2) { … }
catch (IOException e3) { … }
9.8. Exception Information
• Exception object may contain error
information
• e3.getMessage()
• e3.getClass.getName() //returns type
• Own defined exception types can place
more information inside constructors.
9.9. And Finally! … finally
try { code that captures a resource }
catch (MyException e) { handle e }
finally
{ perhaps dispose of captured resources? }
Code in finally{ … } always executes
whether catch executes or not.
9.10 Some Tips
• Don’t use exception handling to replace
testing – Reason: it’s much slower!
• Don’t wrap every code statement in a try
block. Put the whole task in a try block.
• Don’t ignore exceptions with null actions
(just to shut the compiler up). They will
come back and bite you!
10. Sockets & Network
Programming
Recall the structure of a client server architecture
from Section 4.5.
In this section we show how to use Java to
program client side and server side
communication over a network using sockets.
You already have access to one piece of
networking software, namely telnet (recall
Section 4.6). Type in:
telnet time-A.timefeq.bldrdoc.gov 13
You should get a response like:
52088 05-04-25 14:20:17 50 0 0 644.8
UTC(NIST) *
• Here you have asked telnet to connect to a
server run by the NIST in Boulder Colorado
• Gives the time of day measured by a cesium
atomic clock!
• So why is the time not accurate?
• “time of day”service is always connected to
port 13.
• Server software is continuously running in
Boulder. When OS gets a request from a
client for a port 13 connection it wakes up
server and makes connection.
• Connection stays open until it is terminated
by client or server.
• Lets have a look at how to build a simple
client program.
10.1 Client-side Programming
• Lets build a simple Java program that does
the same as our telnet action.
import java.io.*;
import java.net.*; // imports networking package
public class SocketClientTest
{
Public static void main(String[] args)
{
try {
Socket s = new Socket(
“time- A.timefreq.bldrdoc.gov”, 13);
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream( ) ) );
boolean more = true;
while (more) {
String line = in.readLine( );
if (line == null) more = false
else System.out.println(line); }
} catch (IOException e)
{ e.printStackTrace( ) ; }
}
Socket s = new Socket(
“time- A.timefreq.bldrdoc.gov”, 13);
• This opens a Socket that enables
communication in and out of our client
program.
• We pass a network address and a port number
to the socket constructor.
• If connection fails an UnknownHostException
is thrown
• Any other failure gives an IOException
• UnknownHostException is a subclass of
IOException so we just catch the superclass.
• The getInputStream method in java.net.Socket
returns an InputStream object
• Once we have the stream, just read all characters
using readLine,
• Print each line to standard output.
• Server disconnects when readLine returns a null
string.
• Essentially a file interface to network.
10.2 Server-side Programming
ServerSocket s = new ServerSocket(8189);
Establishes a server that monitors port 8189.
Socket incoming = s.accept();
Tells server to wait indefinitely until a client
connects to port 8189.
• accept() method returns a Socket object once
a client send the correct request.
• This is our actual connection
• Use this object to get a socket reader and writer
BufferedReader in = new BufferedReader
(new InputStreamReader(
incoming.getInputStream( ) ) );
PrintWriter out = new PrintWriter
(incoming.getOutputStream( ),
true /*autoFlush*/ );
• To transmit serialized objects we use
ObjectInputStream and ObjectOutputStream
• We can send the client some data with
• Out.println(“Hello! Enter BYE to exit”.”);
• Telnet into this server on port 8189 and you
should get the above greeting!
• Our server will just echo client text
while (!done) {
String line = in.readLine();
if (line != null)
{
out.println(“Echo: “ + line);
if (line.trim().equals(“BYE”)) done = true;
}
else done = true
}
• Finally we close the incoming socket
incoming.close();
•
Every server program has this loop
1. Get a command from client through an
incoming data stream
2. Fetch the information
3. Send the information to the client through
outgoing data stream
4. Goto 1.
• Complete this program (add imports, main
etc) and run it.
• Use telnet to connect to server
Server:127.0.0.1 Port:8189
• IP address 127.0.0.1 is the local loopback
address that denotes the local machine
• Can combine these constructions with
threads to serve multiple clients
• Every time accept() is successful launch a
new thread with that connection.
import java.net.*;
import java.io.*;
import java.util.*;
public class RockScissorsBagServer {
public static void main(String[] args){
try {
ServerSocket sock = new
ServerSocket(4712);
while (true) new
Thread(sock.accept()).start();
}
catch(IOException e) {
System.err.println(e);
}
}
}