1 / 62

Java – intermediate topics

Java – intermediate topics. Part I – Exceptions and Collections Part II – Threads Part III – Swing. Part I – Exceptions and Collections. Exceptions and exception handling What are exceptions? When should you use exceptions? Details How are exceptions generated (thrown)?

debbie
Download Presentation

Java – intermediate topics

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. Java – intermediate topics Part I – Exceptions and Collections Part II – ThreadsPart III – Swing

  2. Part I – Exceptions and Collections • Exceptions and exception handling • What are exceptions? • When should you use exceptions? • Details • How are exceptions generated (thrown)? • How are exceptions handled (caught)? • Runtime exceptions vs. other exceptions. • Collections • What is a collection? • java.util.Collection interface • Iterators • java.util.Iterator interface • Iterator pattern • Decoupling of data structure and iteration logic

  3. What are exceptions? • Exceptions are a mechanism for handling “exceptional” situations which can occur at runtime. • Many languages provide exceptions. • Terminology: • code where something unexpected happens “throws” an exception • code which handles the exceptional situation “catches” the exception – this code is called an exception handler

  4. When are exceptions appropriate? • Exceptions are appropriate to use to signal to a caller a problematic situation which cannot be handled locally. • Example: Consider a file reading component which is used both by an interactive UI and a batch processing component. If the file reading component has a problem (“disk is full”), can it decide locally how to respond? No. It is up to the client to decide how to react. The UI may notify its human user. The batch processor may log the problem, and skip processing of this file.

  5. When are exceptions not appropriate? • It is not appropriate to use the exception mechanism when an exceptional situation can be handled locally. • It is not appropriate to use the exception mechanism in dealing with situations which are not exceptional. • If a particular situation is expected, it should be explicitly checked for. • For example, if a user supplies the name of a file to be read, it is better to check for existence of the file rather than to attempt to read and rely on a thrown exception to give notice if the file doesn’t exist.

  6. How are exceptions generated? • An exception is an object • An exception must derive from the java.lang.Exception class • Detour into inheritance and typing…

  7. Types and subtypes • Every class in Java defines a type. • Every interface in Java defines a type. • Types are arranged into a hierarchy: • classes can extend classes; • interfaces can extends interfaces; • classes can implement interfaces. • Every class except Object has a parent class (which is Object if no other parent is given): every other class has exactly one parent.

  8. Hierarchy for Exceptions (partial) • Object • Throwable • Error • LinkageError • ThreadDeath • VirtualMachineError • Exception • IOException • FileNotFoundException • MalformedURLException • RuntimeException • IndexOutOfBoundsException • NullPointerException

  9. Significance of hierarchy • The type hierarchy is significant, not only for exceptions, but for typing in Java more generally. • A variable declared to be of a given type can be assigned an object of that type, or of any subtype. • We make a distinction between • the declared type of a variable, and • the actual type of the object assigned to it.

  10. How are exceptions generated? • An exception is an object. • An exception must derive from the java.lang.Exception class. • An exception object must be instantiated from an exception class. • new IndexOutOfBoundsException() • An exception must be thrown: • throw new IndexOutOfBoundsException()

  11. What happens when an exception is thrown? • The exception is thrown until one of two things happens: • an exception handler for the thrown exception is found, or • the exception is uncaught (which typically results in program termination). • More technically, the runtime stack is unwound until a handler is found or the stack is empty.

  12. Runtime stack? • Every time a method is called, an invocation record is pushed onto the runtime stack. • An invocation record stores things like: • parameter values • local variables • return value • return location • When a method finishes, its corresponding invocation record is removed (“popped”) from the runtime stack.

  13. Exceptions and flow-of-control • When an exception is thrown, the regular flow of control is interrupted. • Invocation records are popped from runtime stack until an exception handler is found. • Because of this, code in a method after a “throw” is not executed if the throw occurs.

  14. Example public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; }

  15. Example (if x > 0) public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; }

  16. Example (if x <= 0) public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; }

  17. Catching an exception • If you want to catch an exception, you must indicate: • from which segment of code you are prepared to handle an exception • which exception(s) you are going to handle • You can also: • include a “cleanup” case to release resources acquired, regardless of whether an exception was thrown

  18. The try block • To indicate the segment of code from which you are prepared to handle an exception, place it in a try block: stmt1; try { stmt2; stmt3; } stmt4;

  19. A catch block • A catch block is an exception handler for a specific type of exception: try { // code that may throw exception } catch (Exception e) { // code to handle exception }

  20. Multiple catch blocks • Can place many catch blocks (exception handlers) after a try block: try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle an index out of bounds exception } catch (MalformedURLException e) { // code to handle a malformed URL exception } catch (Exception e) { // code to handle a general exception }

  21. Recall there is an exception hierarchy: • Here’s part of the hierarchy: • Exception • IOException • FileNotFoundException • MalformedURLException • RuntimeException • IndexOutOfBoundsException • NullPointerException

  22. Catch block ordering: specific to general • Catch blocks are tried in the order they are written: try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (Exception e) { // code to handle any other exception }

  23. Now consider a slightly different part of the hierarchy: • Here’s part of the hierarchy: • Exception • IOException • FileNotFoundException • MalformedURLException • RuntimeException • IndexOutOfBoundsException • NullPointerException

  24. Catch block ordering: general to specific? • Catch blocks are tried in the order they are written: try { // code that may throw exception } catch (Exception e) { // code to handle any exception } catch (RuntimeException e) { // code to handle a runtime exception // this is never reached! } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception // this is never reached! }

  25. Finally clause • Optional • Used to release resources back to OS • Shared resources are often acquired inside a try block (e.g. a file is opened for writing) • These resources must be released (e.g. the file must be closed so some other piece of code can use it): • if an exception is NOT thrown in the try block • if an exception IS thrown in the try block

  26. Flow of control:no exception is thrown // some code try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code

  27. Flow of control:handled exception (e.g. RuntimeException) is thrown // some code try { // code that throws a RuntimeException } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code

  28. Flow of control:unhandled exception (e.g. FileNotFoundException) is thrown // some code try { // code that throws a RuntimeException } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code

  29. Defining your own exception classes • Since exceptions are just objects derived from the type java.util.Exception, you can define your own. • Won’t go into this unless you think you’ll need it. There are *many* predefined exceptions – one will likely meet your needs.

  30. Part II - Threads • Processes & Threads • Threads & Graphics

  31. Processes and Threads • What is a process? • What is a thread? • two special Java threads • main thread • event-dispatching thread • the Runnable interface

  32. Processes • A program that is running on a computer is called a process. • most consumer OSes allow many processes to run simultaneously • a single program can give rise to many processes • Bob runs Netscape – one process • Sally runs Netscape – another process • multitasking at the operating system level

  33. Threads • Each process has its own (main) thread of execution • A process can spawn several threads • multitasking is happening at the level of the process, not at the level of the operating system • a process with multiple threads is called a multithreaded application

  34. Two Java threads • Every Java program has a main thread of execution. • starts with “public static void main(String [] args)” • Graphical applications have an event-dispatching thread too. • It is important for the proper functioning of graphical, event-driven programs that graphics be run on the event-dispatching thread.

  35. Runnable interface • The Runnable interface specifies one method: publicinterface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ publicabstractvoid run(); }

  36. How is Runnable used? • An object which is Runnable has a run method. • An object which is Runnable can be run in a specific thread. • The javax.swing.SwingUtilities class provides a method, invokeLater, which takes a Runnable, and calls its run method once other events queued on the event-dispatching thread have been handled.

  37. What does this have to do with graphics? • To be “thread safe” graphical applications should run their GUI code on the event-dispatching thread. • They do this by starting their GUI on the event-dispatching thread • write the GUI creation code in a Runnable • pass this object to the invokeLater method.

  38. Part III - Swing • Introduction to Swing • Containers (graphical) • Components • Layout managers • Event handling • Inner classes • Swing components in (more) detail • Containers • top-level containers • general containers • special-purpose containers • Controls • Views (uneditable displays) • Editors • Layout managers in (more) detail

  39. Graphical containers • All graphical elements are contained inside some graphical container, except the so-called “top-level” containers. • Containers can contain other containers • Top-level containers: • JFrame • JDialog • JApplet

  40. Example • Creating just a frame • new javax.swing.JFrame() • Creating a frame with a title • new javax.swing.JFrame(“My title”) • Making the frame visible: • call setVisible(true) on the frame • Making application close when window is closed: • call setDevaultCloseOperation(JFrame.EXIT_ON_CLOSE) on the frame • Go look at example_set_1

  41. Adding components • Top-level containers have multiple panes • Content pane is the one which holds components • call getContentPane() on frame to get frame’s content pane • call add(…) on content pane to add a component • starting with Java 5, you can add components to a JFrame’s content pane by calling the add method directly on the JFrame

  42. A simple component • A JLabel is a component that can display text or an image. • Go look at example_set_2

  43. Layout managers • What happens if we add another JLabel? • Go look at example_set_3

  44. Another component • A JButton is a component which is typically set up to react to clicks. • Clicks on buttons, mouse movements, etc. are all considered events. • A program can react to events by setting up event handlers. • Like an exception handler, an event handler defines what should happen when a particular event occurs.

  45. Event handling – 1 • The component which gives rise to an event is decoupled from the part of the code that handles the event. • This is called the observer pattern. • General form: • www.research.ibm.com/designpatterns/example.htm

  46. Event handling – 2 • Observer pattern in Java • An observer is called a listener in Java • Button clicks are “ActionEvents”. • Handlers for ActionEvents are ActionListeners. • An event-generator can have many listeners • Use “addActionListener” method to register a listener with a component

  47. Inner Classes • An inner class is a class defined inside another class. • An inner class is within the scope of the surrounding class (and therefore has access to private variables and methods defined in class). • An anonymous inner class is an inner class defined without a name (a one-off class) • saw this earlier with Runnable interface implementation • Inner classes are often used to define event handlers, especially anonymous inner classes.

  48. Event handling - 3 • Go look at example_set_4

  49. Putting it all together • Go look at example_set_5

  50. Containers • Top-level containers • JApplet, JFrame, JDialog (and subclasses) • They can serve as the top of a (graphical) containment hierarchy (i.e. they don’t need to be contained within another container). • General containers • panels, scroll panes, split panes and tabbed panes • They provide fairly general ways of organizing information visually. • Special-purpose containers • Won’t go into these here.

More Related