9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible...

43
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!
  • date post

    18-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    2

Transcript of 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible...

Page 1: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

9. ExceptionsAn 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!

Page 2: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 3: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 4: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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.

Page 5: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

9.1. Exception Handling

All exception handling has the same goals:

1. Anticipate the error by the user/system2. Return the program to a safe state that

enables the user to execute other commands

3. Inform the user of the error’s cause4. Allow the user to save work and terminate

the program gracefully.

Page 6: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

Throwable

Error Exception

RuntimeException

IOExceptionThe Java

Exception Hierarchy

Page 7: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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

Page 8: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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 wrongPublic String readLine() throws IOException

Page 9: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 10: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

4 Ways to throw an Exception1. 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

Page 11: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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??

Page 12: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

9.2. How to Throw an Exception

• Suppose we are writing a file reader …

• Header promises 1024 bytes …

• But ... end of file after 600 bytes!

1. Decide what kind of exception to throw

2. Look up Java exception hierarchy

3. Subclass of IOException seems natural

4. Settle on EOFException

Page 13: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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}

Page 14: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• If an existing exception class works for you then throwing is easy

1. Find an appropriate class2. Make an object of that class3. Throw it

• AlsoEOFException e = new EOFException();throw e;

Page 15: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

9.3. Error Messages

Often have a second constructor with a String

parameter.

String message =

“Content-length: “ + len “ + “received” + n;

throw new EOFException(message);

Page 16: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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

Page 17: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

class MyFileException extends IOException

{

public MyFileException ( ) { … }

public MyFileException(String message)

{

super(message);

}

}

Page 18: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

String myReadData(BufferedReader in)throws MyFileException{

…if (ch = -1) // EOF encountered{

if (n < len) throw new MyFileException(“Help!”);

}return s}

Page 19: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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.

Page 20: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

9.6. try/catch block

try

{

mycode …

}

catch (ExceptionType e)

{

handler for just this exception type …

}

Page 21: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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

Page 22: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

public void read(BufferedReader reader){

try {…String line = reader.readLine();…

}catch IOException exception){

exception.printStackTrace();}

}

Page 23: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• Can also just throw an exception without catching it.

public void read(BufferedReader reader) throws IOException

{

String line = reader.readLine();

}

Page 24: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 25: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

9.7. Catching Multiple Exceptions

try { mycode }

catch (BadURLException e1) { … }

catch (UnknownHostException e2) { … }

catch (IOException e3) { … }

Page 26: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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.

Page 27: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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.

Page 28: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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!

Page 29: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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.

Page 30: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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) *

Page 31: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 32: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 33: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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

{

Page 34: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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 = falseelse System.out.println(line); }

} catch (IOException e){ e.printStackTrace( ) ; }

}

Page 35: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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

Page 36: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 37: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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.

Page 38: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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*/ );

Page 39: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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

Page 40: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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 socketincoming.close();

Page 41: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 42: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

• 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.

Page 43: 9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,

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);}

}}