CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Handling errors Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Handling errors Writing robust code. 16/12/2004Lecture 10: Handling Errors2 Main concepts to be covered Defensive programming. –Anticipating that things.
CPSC150 Week 13 Chapter 12 Exceptions (from slides provided by textbook web site)
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files.
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
Building Graphical User Interfaces Overview Constructing GUIs Interface components GUI layout Event handling Objects First with Java - A Practical.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files Section 2.13, Section 8.8.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
CC1007NI: Further Programming Week 5 Dhruba Sen Module Leader (Islington College)
Handling errors Exception handling and throwing Simple file processing.
Slides Credit Umair Javed LUMS Web Application Development.
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
Lecture 4. Greenfoot 1 Pablo Romero, Department of Informatics Kinect in Greenfoot.
COMP Exception Handling Yi Hong June 10, 2015.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
OOP (Java): GUI Intro/ OOP Objectives – –use an image viewer application to introduce Java's GUI features Semester 2,
Objects First With Java A Practical Introduction Using BlueJ Handling errors 1.0.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Objects First With Java A Practical Introduction Using BlueJ Building Graphical User Interfaces 2.0.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
1 COS 260 DAY 24 Tony Gauvin. 2 Agenda Questions? 10 th Mini Quiz Corrected –So-so results Capstone progress report over due Course evaluations Assignment.
OOP (Java): Exceptions/ OOP Objectives – –examine Java's exception handling Semester 2, Exceptions.
Handling errors Main concepts to be covered Defensive programming –Anticipating that things could go wrong Exception handling and throwing Error.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Objects First With Java A Practical Introduction Using BlueJ Building Graphical User Interfaces (GUIs) Week
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
Building Graphical User Interfaces Overview Constructing GUIs Interface components GUI layout Event handling © 2017 Pearson Education, Inc. Hoboken,
CSE 205 Exam 2 Review By Cheri Thompson and Katherine Kincade.
13 Handling errors. 2 Förel. 3Object oriented programming, DAT050, DAI2, 16/17, lp 1 Main concepts to be covered Defensive programming. –Anticipating.
A Quick Java Swing Tutorial
“Form Ever Follows Function” Louis Henri Sullivan
Introduction to Exceptions in Java
Building Graphical User Interfaces
COS 260 DAY 23 Tony Gauvin.
Exceptions 10-Nov-18.
COS 260 DAY 27 Tony Gauvin.
COS 260 DAY 23 Tony Gauvin.
COS 260 DAY 23 Tony Gauvin.
COS 260 DAY 26 Tony Gauvin.
COS 260 DAY 26 Tony Gauvin.
Web Design & Development Lecture 7
1 Graphical User Interfaces
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exception Handling Contents
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions

CPSC150 Java Lynn Lambert Rest of GUIs Overview of Swing Overview of Swing (from Dr. Flores’ notes from Liang) JOptionPane example JOptionPane example MenuBars MenuBars

CPSC150 Java Lynn Lambert Java GUI The Java GUI packages GUI classes are found in two packages: AWT (Abstract Windows Toolkit) Swing Swing components are based on AWT classes Java 2 released Swing as an alternative to AWT AWT uses platform-specific GUI components Swing is less reliant on platform-specific components more less heavyweight components AWT lightweight components Swing reliance on platform-specific GUI components

CPSC150 Java Lynn Lambert Java GUI The Java GUI inheritance hierarchy Object Color Container Component LayoutManager Panel Window Applet Frame Dialog JComponent JApplet JFrame JDialog lightweight heavyweight Swing AWT

CPSC150 Java Lynn Lambert Java GUI The Java GUI inheritance hierarchy JComponent JMenuBar AbstractButton JScrollPane JPanel JTextComponent JLabel JComboBox JMenuItem JButton JTextArea JTextField JPasswordField … etc. Swing …

CPSC150 Java Lynn Lambert Rest of GUIs Overview of Swing Overview of Swing JOptionPane example JOptionPane example (from Dr. Flores and from Chapter 11) MenuBars MenuBars

CPSC150 Java Lynn Lambert The JOptionPane Class Java comes with simple ready-made dialogs showConfirmDialog int result = JOptionPane.showConfirmDialog( frame, "These are your options", "confirm dialog", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); int result = JOptionPane.showConfirmDialog( frame, "These are your options", "confirm dialog", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); parent frame message option type (one of): DEFAULT_OPTION YES_NO_OPTION YES_NO_CANCEL_OPTION OK_CANCEL_OPTION option type (one of): DEFAULT_OPTION YES_NO_OPTION YES_NO_CANCEL_OPTION OK_CANCEL_OPTION title message type result value (one of): OK_OPTION YES_OPTION NO_OPTION CANCEL_OPTION CLOSE_OPTION result value (one of): OK_OPTION YES_OPTION NO_OPTION CANCEL_OPTION CLOSE_OPTION Ready-to-use Dialogs

CPSC150 Java Lynn Lambert The JOptionPane Class Java comes with simple ready-made dialogs showOptionDialog String[] options = {"BMW","Mini","Mustang","Porsche"}; int result = JOptionPane.showOptionDialog( frame, "Choose a car:", "options dialog", -1, new ImageIcon("car.gif"), options, options[1]); String[] options = {"BMW","Mini","Mustang","Porsche"}; int result = JOptionPane.showOptionDialog( frame, "Choose a car:", "options dialog", -1, new ImageIcon("car.gif"), options, options[1]); parent frame option type title message result value (one of): 0…options.length-1 CLOSE_OPTION result value (one of): 0…options.length-1 CLOSE_OPTION message type icon options selection (  options) options one label per button options one label per button Ready-to-use Dialogs

CPSC150 Java Lynn Lambert Rest of GUIs Overview of Swing Overview of Swing JOptionPane example JOptionPane example MenuBars MenuBars (from BlueJ book notes)

CPSC150 Java Lynn Lambert Adding menus JMenuBar JMenuBar Displayed below the title. Displayed below the title. Contains the menus. Contains the menus. JMenu JMenu e.g. File. Contains the menu items. e.g. File. Contains the menu items. JMenuItem JMenuItem e.g. Open. Individual items. e.g. Open. Individual items.

CPSC150 Java Lynn Lambert private void makeMenuBar(JFrame frame) { JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); // create the File menu JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); JMenuItem openItem = new JMenuItem("Open"); fileMenu.add(openItem); JMenuItem quitItem = new JMenuItem("Quit"); fileMenu.add(quitItem); }

CPSC150 Java Lynn Lambert Anonymous action listener JMenuItem openItem = new JMenuItem("Open"); openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } });

CPSC150 Java Lynn Lambert Anonymous class elements openItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } ); Anonymous object creation Actual parameter Class definition

CPSC150 Java Lynn Lambert Struts and Glue Invisible components used as spacing. Invisible components used as spacing. Available from the Box class. Available from the Box class. Strut: fixed size. Strut: fixed size. Component createHorizontalStrut(int width) Component createHorizontalStrut(int width) Component createVerticalStrut(int height) Component createVerticalStrut(int height) Glue: fills available space. Glue: fills available space. Component createHorizontalGlue() Component createHorizontalGlue() Component createVerticalGlue() Component createVerticalGlue()

CPSC150 Java Lynn Lambert Pushing a menu to the right menu = new JMenu("File"); menubar.add(menu); menu = new JMenu("Filter"); menubar.add(menu); menubar.add(Box.createHorizontalGlue()); menu = new JMenu("Help"); menubar.add(menu); Glue (invisible)

CPSC150 Java Lynn Lambert Buttons and nested layouts (for information only) A GridLayout inside a FlowLayout inside a BorderLayout.

CPSC150 Java Lynn Lambert Borders (for information only) Used to add decoration around components. Used to add decoration around components. Defined in javax.swing.border Defined in javax.swing.border BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, TitledBorder. BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, TitledBorder.

CPSC150 Java Lynn Lambert Adding spacing (for information only) JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setBorder(new EmptyBorder(6, 6, 6, 6)); // Specify the layout manager with nice spacing contentPane.setLayout(new BorderLayout(6, 6)); imagePanel = new ImagePanel(); imagePanel.setBorder(new EtchedBorder()); contentPane.add(imagePanel, BorderLayout.CENTER);

CPSC150 Java Lynn Lambert Other components (for information only) Slider Slider Spinner Spinner Tabbed pane Tabbed pane Scroll pane Scroll pane

CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions

CPSC150 Java Lynn Lambert main Java programs may be run outside BlueJ (and outside of any IDE) Java programs may be run outside BlueJ (and outside of any IDE) Java programs are run on a JVM Java programs are run on a JVM Java programs run outside of blueJ start with the method called main Java programs run outside of blueJ start with the method called main

CPSC150 Java Lynn Lambert Compiling Java programs Files created in BlueJ can be run ins or outside or Bluej. (Files created outside of BlueJ need “Open non-BlueJ”) Files created in BlueJ can be run ins or outside or Bluej. (Files created outside of BlueJ need “Open non-BlueJ”) To compile outside of Bluej, type in terminal window: To compile outside of Bluej, type in terminal window: javac nameofprogram.java javac nameofprogram.java syntax errors will be reported in terminal window syntax errors will be reported in terminal window when syntax error free,.class file will be created (e.g., nameofprogram.java) when syntax error free,.class file will be created (e.g., nameofprogram.java) NOTE: name of class MUST be the same as the name of the file (in BlueJ and out) NOTE: name of class MUST be the same as the name of the file (in BlueJ and out)

CPSC150 Java Lynn Lambert Running Java programs To run outside of BlueJ (on JVM), type: To run outside of BlueJ (on JVM), type: java nameofprogram where nameofprogram is file name except.class part where nameofprogram is file name except.class part NOT java nameofprogram.class NOT java nameofprogram.class java nameofprogram.class results in the following error: results in the following error: Exception in thread "main" java.lang.NoClassDefFoundError: nameofprogram/class

CPSC150 Java Lynn Lambert main public static void main(String[] args) { // usually not much here. create an object, and go } so it can be called outside the class so an object doesn’t have to be created in order to use it in case arguments on command line (e.g., cp file1 file2)

CPSC150 Java Lynn Lambert main method rules Because it is static, all methods that call it must be static. Because it is static, all methods that call it must be static. So, don’t have many methods call it So, don’t have many methods call it Create an object, and go from there Create an object, and go from there Sometimes, especially with GUIs, no return from main. Sometimes, especially with GUIs, no return from main. ctrl-c to end program ctrl-c to end program

CPSC150 Java Lynn Lambert main examples All 150lab examples have main All 150lab examples have main compile these outside compile these outside run them run them Exercise: Create a main method for your Rainfall program (program 3). Create a rainfall object in main and call it. Run the program. Exercise: Create a main method for your Rainfall program (program 3). Create a rainfall object in main and call it. Run the program.

CPSC150 Java Lynn Lambert more on static: Math library Math library contains methods to do math Math library contains methods to do math log, max, sqrt, round, abs, etc. log, max, sqrt, round, abs, etc. All methods are static All methods are static Why? Why?

CPSC150 Java Lynn Lambert class Myclass { private double mynbr; public Myclass(double val) { mynbr = val; } public double getSqrt( ) { return Math.sqrt(mynbr); }} With Math Static methods

CPSC150 Java Lynn Lambert With Math non-static methods class Myclass { private double mynbr; public Myclass(double val) {mynbr = val;} public double getSqrt( ) { Math stupidobject = new Math( ); // create object in order to use sqrt method. no other reason. // object is not being used. NOT like changeColor method – // changeColor is being done on object. OR, getTitle for Item. return suptidobject.sqrt(mynbr); }}

CPSC150 Java Lynn Lambert Static vs non-static Most methods are done for the objects. should be non-static Most methods are done for the objects. should be non-static Some methods exist for the class. should be static Some methods exist for the class. should be static Any methods main calls must be static Any methods main calls must be static Lesson: main shouldn’t call many methods Lesson: main shouldn’t call many methods

CPSC150 JavaLynn Lambert Week 13 Rest of Guis (from Bluej web page) mainExceptions (from slides provided by textbook web site)

CPSC150 JavaLynn Lambert Handling errors 2.1

CPSC150 Java Lynn Lambert Some causes of error situations Incorrect implementation. Incorrect implementation. Does not meet the specification. Does not meet the specification. Inappropriate object request. Inappropriate object request. E.g., invalid index. E.g., invalid index. Inconsistent or inappropriate object state. Inconsistent or inappropriate object state. E.g. arising through class extension. E.g. arising through class extension.

CPSC150 Java Lynn Lambert Not always programmer error Errors often arise from the environment: Errors often arise from the environment: Incorrect URL entered. Incorrect URL entered. Network interruption. Network interruption. File processing is particular error-prone: File processing is particular error-prone: Missing files. Missing files. Lack of appropriate permissions. Lack of appropriate permissions.

CPSC150 Java Lynn Lambert Exploring errors Explore error situations through the address-book projects. Explore error situations through the address-book projects. Two aspects: Two aspects: Error reporting. Error reporting. Error handling. Error handling.

CPSC150 Java Lynn Lambert Issues to be addressed How much checking by a server on method calls? How much checking by a server on method calls? How to report errors? How to report errors? What if no user at the other end (e.g., GUI)? How can a client anticipate failure? How can a client anticipate failure? How should a client deal with failure? How should a client deal with failure?

CPSC150 Java Lynn Lambert An example Create an AddressBook object. Create an AddressBook object. Try to remove an entry. Try to remove an entry. A runtime error results. A runtime error results. Whose ‘fault’ is this? Whose ‘fault’ is this? Anticipation and prevention are preferable to apportioning blame. Anticipation and prevention are preferable to apportioning blame.

CPSC150 Java Lynn Lambert Argument values Arguments represent a major ‘vulnerability’ for a server object. Arguments represent a major ‘vulnerability’ for a server object. Constructor arguments initialize state. Constructor arguments initialize state. Method arguments often contribute to behavior. Method arguments often contribute to behavior. Argument checking is one defensive measure. Argument checking is one defensive measure.

CPSC150 Java Lynn Lambert Checking the key public void removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; }

CPSC150 Java Lynn Lambert Server error reporting How to report illegal arguments? How to report illegal arguments? To the user? To the user? Is there a human user? Is there a human user? Can they solve the problem? Can they solve the problem? To the client object? To the client object? Return a diagnostic value Return a diagnostic value

CPSC150 Java Lynn Lambert Returning a diagnostic (Exception handling without using Java’s exception handling) public boolean removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; return true; } else { return false; }

CPSC150 Java Lynn Lambert Client responses Test the return value. Test the return value. Attempt recovery on error. Attempt recovery on error. Avoid program failure. Avoid program failure. Ignore the return value. Ignore the return value. Cannot be prevented. Cannot be prevented. Likely to lead to program failure. Likely to lead to program failure. Create something client cannot ignore: Create something client cannot ignore: an exception an exception

CPSC150 Java Lynn Lambert Exception-throwing principles Exceptions are part of many languages, central to Java. Exceptions are part of many languages, central to Java. A special language feature. A special language feature. No ‘special’ return value needed. No ‘special’ return value needed. Errors cannot be ignored in the client. Errors cannot be ignored in the client. The normal flow-of-control is interrupted. The normal flow-of-control is interrupted. Specific recovery actions are encouraged. Specific recovery actions are encouraged.

CPSC150 Java Lynn Lambert Exceptions Exceptions are “thrown” by the method finding the problem Exceptions are “thrown” by the method finding the problem Exceptions are “caught” by the method dealing with the problem Exceptions are “caught” by the method dealing with the problem maintains integrity and decoupling maintains integrity and decoupling

CPSC150 Java Lynn Lambert Throwing an exception /** * Look up a name or phone number and return the * corresponding contact details. key The name or number to be looked up. The details corresponding to the key, * or null if there are none matching. NullPointerException if the key is null. */ public ContactDetails getDetails(String key) { if(key == null){ throw new NullPointerException( "null key in getDetails"); } return (ContactDetails) book.get(key); }

CPSC150 Java Lynn Lambert Throwing an exception An exception object is constructed: An exception object is constructed: new ExceptionType("..."); new ExceptionType("..."); The exception object is thrown: The exception object is thrown: throw... throw... Javadoc documentation: Javadoc ExceptionType ExceptionType reason

CPSC150 Java Lynn Lambert The exception class hierarchy

CPSC150 Java Lynn Lambert Exception categories Checked exceptions Checked exceptions Subclass of Exception Subclass of Exception Use for anticipated failures. Use for anticipated failures. Where recovery may be possible. Where recovery may be possible. Often not a programming problem (e.g., file not found) Often not a programming problem (e.g., file not found) Unchecked exceptions Unchecked exceptions Subclass of RuntimeException Subclass of RuntimeException Use for unanticipated failures. Use for unanticipated failures. Where recovery is unlikely. Where recovery is unlikely. Often, a programming problem (e.g., index out of bounds) Often, a programming problem (e.g., index out of bounds) Third category: errors Third category: errors

CPSC150 Java Lynn Lambert The effect of an exception The throwing method finishes prematurely. The throwing method finishes prematurely. No return value is returned. No return value is returned. Control does not return to the client’s point of call. Control does not return to the client’s point of call. So the client cannot carry on regardless. So the client cannot carry on regardless. A client may ‘catch’ an exception. A client may ‘catch’ an exception.

CPSC150 Java Lynn Lambert Unchecked exceptions Use of these is ‘unchecked’ by the compiler. Use of these is ‘unchecked’ by the compiler. Cause program termination if not caught. Cause program termination if not caught. This is the normal practice. This is the normal practice. IllegalArgumentException is a typical example. IllegalArgumentException is a typical example.

CPSC150 Java Lynn Lambert Argument checking public ContactDetails getDetails(String key) { if(key == null) { throw new NullPointerException( "null key in getDetails"); } if(key.trim().length() == 0) { throw new IllegalArgumentException( "Empty key passed to getDetails"); } return (ContactDetails) book.get(key); }

CPSC150 Java Lynn Lambert Preventing object creation public ContactDetails(String name, String phone, String address) { if(name == null) { name = ""; } if(phone == null) { phone = ""; } if(address == null) { address = ""; } this.name = name.trim(); this.phone = phone.trim(); this.address = address.trim(); if(this.name.length() == 0 && this.phone.length() == 0) { throw new IllegalStateException( "Either the name or phone must not be blank."); }

CPSC150 Java Lynn Lambert public class Myexcept { private int x; public Myexcept() { x = 0; } { x = 0; } public int sampleMethod(int y) { if (y == 0) { throw new ArithmeticException( throw new ArithmeticException( "in SampleMethod, y, a denominator, is 0"); "in SampleMethod, y, a denominator, is 0"); } y= x /y; y= x /y; return y; return y; } // …

CPSC150 Java Lynn Lambert public static void main(String args[ ]) public static void main(String args[ ]) { Myexcept m = new Myexcept(); Myexcept m = new Myexcept(); System.out.println("m with 4 is " + m.sampleMethod(4)); System.out.println("m with 4 is " + m.sampleMethod(4)); System.out.println("m with 0 is " + System.out.println("m with 0 is " + m.sampleMethod(0)); m.sampleMethod(0)); System.out.println("all done"); System.out.println("all done"); } // end main } // end main } // end class

CPSC150 Java Lynn Lambert public static void main(String args[ ]) { except m = new except(); except m = new except(); System.out.println("m with 4 is " + System.out.println("m with 4 is " + m.sampleMethod(4)); m.sampleMethod(4)); try { try { System.out.println("m with 0 is " + System.out.println("m with 0 is " + m.sampleMethod(0)); m.sampleMethod(0)); } catch (ArithmeticException e) { catch (ArithmeticException e) { System.out.println("don't call sample method with 0"); System.out.println("don't call sample method with 0"); } System.out.println("all done"); System.out.println("all done"); }

CPSC150 Java Lynn Lambert public class Test { public static void main(String args[]) { int n = 0; String s = null; boolean valid = false; while (!valid) try { s = JOptionPane.showInputDialog( null, "Enter an integer:" ); n = Integer.parseInt( s ); valid = true; } catch(Exception e) { if (s == null) break; else JOptionPane.showMessageDialog( null, "Enter a valid number" ); } if (valid) JOptionPane.showMessageDialog( null, "The number is " + n ); }

CPSC150 Java Lynn Lambert Checked Exceptions Previous examples all unchecked exceptions Previous examples all unchecked exceptions unchecked exceptions should not happen; mostly result in program termination unchecked exceptions should not happen; mostly result in program termination Checked exceptions are meant to be caught. Checked exceptions are meant to be caught. The compiler ensures that their use is tightly controlled. The compiler ensures that their use is tightly controlled. In both server and client. In both server and client. Used properly, failures may be recoverable. Used properly, failures may be recoverable.

CPSC150 Java Lynn Lambert Some Checked Exceptions ClassNotFoundException ClassNotFoundException ClassNotFoundException IOException IOException IOException NoSuchFieldException NoSuchFieldException NoSuchFieldException ServerNotActiveException ServerNotActiveException ServerNotActiveException UnsupportedFlavorException UnsupportedFlavorException UnsupportedFlavorException

CPSC150 Java Lynn Lambert The throws clause Methods throwing a checked exception must include a throws clause: public void saveToFile(String destinationFile) throws IOException Methods throwing a checked exception must include a throws clause: public void saveToFile(String destinationFile) throws IOException (NOT throw) throw is when the exception is thrown (NOT throw) throw is when the exception is thrown

CPSC150 Java Lynn Lambert throws must include throws in methods that throw checked exceptions must include throws in methods that throw checked exceptions how do I know? how do I know? javadoc/syntax errors javadoc/syntax errors

CPSC150 Java Lynn Lambert The try statement Clients catching an exception must protect the call with a try statement: try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } Clients catching an exception must protect the call with a try statement: try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. }

CPSC150 Java Lynn Lambert The try statement try{ addressbook.saveToFile(filename); tryAgain = false; } catch(IOException e) { System.out.println("Unable to save to " + filename); tryAgain = true; } 1. Exception thrown from here 2. Control transfers to here

CPSC150 Java Lynn Lambert Catching multiple exceptions try in order that they appear try {... ref.process();... } catch(EOFException e) { // Take action on an end-of-file exception.... } catch(FileNotFoundException e) { // Take action on a file-not-found exception.... }

CPSC150 Java Lynn Lambert The finally clause try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } finally { Perform any actions here common to whether or not an exception is thrown. }

CPSC150 Java Lynn Lambert The finally clause A finally clause is executed even if a return statement is executed in the try or catch clauses. A finally clause is executed even if a return statement is executed in the try or catch clauses. A uncaught or propagated exception still exits via the finally clause. A uncaught or propagated exception still exits via the finally clause.

CPSC150 Java Lynn Lambert Error recovery Clients should take note of error notifications. Clients should take note of error notifications. Check return values. Check return values. Don’t ‘ignore’ exceptions. Don’t ‘ignore’ exceptions. Include code to attempt recovery. Include code to attempt recovery. Will often require a loop. Will often require a loop.

CPSC150 Java Lynn Lambert Attempting recovery // Try to save the address book. boolean successful = false; int attempts = 0; do { try { addressbook.saveToFile(filename); successful = true; } catch(IOException e) { System.out.println("Unable to save to " + filename); attempts++; if(attempts < MAX_ATTEMPTS) { filename = an alternative file name; } } while(!successful && attempts < MAX_ATTEMPTS); if(!successful) { Report the problem and give up; }

CPSC150 Java Lynn Lambert Error avoidance Clients can often use server query methods to avoid errors. Clients can often use server query methods to avoid errors. More robust clients mean servers can be more trusting. More robust clients mean servers can be more trusting. Unchecked exceptions can be used. Unchecked exceptions can be used. Simplifies client logic. Simplifies client logic. May increase client-server coupling. May increase client-server coupling.

CPSC150 JavaLynn Lambert Files Chapter 12 continued

CPSC150 Java Lynn Lambert Text input-output: tie to exceptions Input-output is particularly error-prone. Input-output is particularly error-prone. It involves interaction with the external environment. It involves interaction with the external environment. The java.io package supports input-output. The java.io package supports input-output. java.io.IOException is a checked exception. java.io.IOException is a checked exception. cannot do files without exceptions cannot do files without exceptions

CPSC150 Java Lynn Lambert Files To use files, use File class To use files, use File class File class can’t read/write File class can’t read/write To read/write files, use Reader/Writer classes To read/write files, use Reader/Writer classes File input can be text-based (what we’ll do), stream-based File input can be text-based (what we’ll do), stream-based

CPSC150 Java Lynn Lambert Readers, writers, streams Readers and writers deal with textual input. Readers and writers deal with textual input. Based around the char type. Based around the char type. Streams deal with binary data. Streams deal with binary data. Based around the byte type. Based around the byte type. The address-book-io project illustrates textual IO. The address-book-io project illustrates textual IO.

CPSC150 Java Lynn Lambert Text output Use the FileWriter class. Use the FileWriter class. Tie File object to diskfile name Tie File object to diskfile name Open a FileWriter; tie to File. Open a FileWriter; tie to File. Write to the FileWriter. Write to the FileWriter. Close the FileWriter. Close the FileWriter. Failure at any point results in an IOException. Failure at any point results in an IOException.

CPSC150 Java Lynn Lambert Text output try { FileWriter writer = new FileWriter("name of file"); while(there is more text to write) {... writer.write(next piece of text);... } writer.close(); } catch(IOException e) { something went wrong with accessing the file }

CPSC150 Java Lynn Lambert Text input Use the FileReader class. Use the FileReader class. Augment with BufferedReader for line- based input. Augment with BufferedReader for line- based input. Open a file. Open a file. Read from the file. Read from the file. Close the file. Close the file. Failure at any point results in an IOException. Failure at any point results in an IOException.

CPSC150 Java Lynn Lambert Text input try { BufferedReader reader = new BufferedReader( new FileReader("filename")); String line = reader.readLine(); while(line != null) { do something with line line = reader.readLine(); } reader.close(); } catch(FileNotFoundException e) { the specified file could not be found } catch(IOException e) { something went wrong with reading or closing }

CPSC150 Java Lynn Lambert Write a program to count number of lines in a file and write the number to an output file java countlines myinfile.txt myoutfile.txt would return 2 if file is: This is a file with two lines. myinfile.txt

CPSC150 Java Lynn Lambert import java.io.*; public class countlines { // all methods that do something inserted here public static void main(String[] args) public static void main(String[] args) { if (args.length != 2) if (args.length != 2) { System.out.println("to run, type: 'countlines filein fileout'"); System.out.println("to run, type: 'countlines filein fileout'"); System.exit(1); System.exit(1); } // create a new countline object with first arg as input file, second as output countlines cl = new countlines(args[0], args[1]); countlines cl = new countlines(args[0], args[1]);}}

CPSC150 Java Lynn Lambert // constructor // constructor public countlines(String filein, String fileout) { try { try { int countwords = readfrom(filein); int countwords = readfrom(filein); writeto(fileout, countwords); writeto(fileout, countwords); } catch (IOException e) { catch (IOException e) { // will catch any IO exception not caught by readfrom and writeto System.out.println("Problems with IO. Program aborted without successful write."); System.out.println("Problems with IO. Program aborted without successful write."); } }

CPSC150 Java Lynn Lambert // file output. method called from constructor public void writeto(String fileout, int nbrlines) throws IOException // must have “throws IOException” even though // no “throw statement” { File outfile = new File(fileout); File outfile = new File(fileout); FileWriter fw = new FileWriter(outfile); FileWriter fw = new FileWriter(outfile); // usually a loop to write out all information // usually a loop to write out all information // write to writer, not file // write to writer, not file fw.write("There were " + nbrlines + " lines in the input file."); fw.write("There were " + nbrlines + " lines in the input file."); fw.close(); fw.close(); }

CPSC150 Java Lynn Lambert public int readfrom(String filename) throws IOException public int readfrom(String filename) throws IOException { int countlines = 0; int countlines = 0; try { try { File infile = new File(filename); File infile = new File(filename); BufferedReader reader = new BufferedReader(new FileReader(infile)); BufferedReader reader = new BufferedReader(new FileReader(infile)); String line; String line; line = reader.readLine(); line = reader.readLine(); while (line != null) { while (line != null) { System.out.println(line); // for debugging only; System.out.println(line); // for debugging only; countlines++; countlines++; line = reader.readLine(); line = reader.readLine(); } reader.close(); reader.close(); } catch (FileNotFoundException e) { catch (FileNotFoundException e) { System.out.println("The input file was not there"); System.out.println("The input file was not there"); } return countlines; return countlines; }

CPSC150 Java Lynn Lambert Other Wrappers Can break string read up using StringTokenizer Can break string read up using StringTokenizer Can read non-text files with FileReader and Tokenizer (breaks fields up to be read) Can read non-text files with FileReader and Tokenizer (breaks fields up to be read)