1 / 43

9. Exceptions

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 :

xarles
Download Presentation

9. Exceptions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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, the JVM generates an exception. If we don’t catch the exception, the program crashes!

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

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

  4. When an exception occurs, Java allows a method to terminate abnormally • It throws an object that encapsulates error information • It does not return a value • It exits immediately • Execution does not resume at the point of method call • JVM searches for an exception handler • If none is found, the program crashes.

  5. 9.1. Exception Handling All exception handling has the same goals: • Anticipate the error by the user/system • Return the program to a safe state that enables the user to execute other commands • Inform the user of the error’s cause • Allow the user to save work and terminate the program gracefully.

  6. Throwable Error Exception IO Exception Runtime Exception The Java Exception Hierarchy

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

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

  9. RuntimeExceptioncaused 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.

  10. 4 Ways to throw an Exception • Calling a method that throws a checked exception, e.g. readLine • Code detects an error and generates checked exception with throw statement • Programming error e.g. a[-1] =0; generates an unchecked exceptionArrayIndexOutOfBoundsException 4. JVM or runtime library internal error

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

  12. 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! • Decide what kind of exception to throw • Look up Java exception hierarchy • Subclass of IOException seems natural • Settle on EOFException

  13. 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 }

  14. If an existing exception class works for you then throwing is easy • Find an appropriate class • Make an object of that class • Throw it • Also EOFException e = new EOFException(); throw e;

  15. 9.3. Error Messages Often have a second constructor with a String parameter. String message = “Content-length: “ + len “ + “received” + n; throw new EOFException(message);

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

  17. class MyFileException extends IOException { public MyFileException ( ) { … } public MyFileException(String message) { super(message); } }

  18. String myReadData(BufferedReader in) throws MyFileException { … if (ch = -1) // EOF encountered { if (n < len) throw new MyFileException(“Help!”); } return s }

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

  20. 9.6. try/catch block try { mycode … } catch (ExceptionType e) { handler for just this exception type … }

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

  22. public void read(BufferedReader reader) { try { … String line = reader.readLine(); … } catch IOException exception) { exception.printStackTrace(); } }

  23. Can also just throw an exception without catching it. public void read(BufferedReader reader) throws IOException { … String line = reader.readLine(); … }

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

  25. 9.7. Catching Multiple Exceptions try { mycode } catch (BadURLException e1) { … } catch (UnknownHostException e2) { … } catch (IOException e3) { … }

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

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

  28. 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!

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

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

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

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

  33. 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 {

  34. 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( ) ; } }

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

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

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

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

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

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

  41. Every server program has this loop • Get a command from client through an incoming data stream • Fetch the information • Send the information to the client through outgoing data stream • Goto 1.

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

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

More Related