82
Java Lynn Lambert CPSC150 Week 13 Week 13 Rest of Guis (from Bluej Rest of Guis (from Bluej web page) web page) main main Exceptions Exceptions

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

  • View
    215

  • Download
    1

Embed Size (px)

Citation preview

Java Lynn Lambert CPSC150

Week 13Week 13

Rest of Guis (from Bluej web Rest of Guis (from Bluej web page)page)

mainmain

ExceptionsExceptions

Java Lynn Lambert CPSC150

Rest of GUIsRest of GUIs

Overview of SwingOverview of Swing(from Dr. Flores’ notes from Liang)(from Dr. Flores’ notes from Liang)

JOptionPane exampleJOptionPane example MenuBarsMenuBars

Java Lynn Lambert CPSC150

Java GUIJava GUIThe Java GUI packagesGUI 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

moremore lessless

heavyweightcomponents

AWT

lightweightcomponents

Swing

reliance on platform-specific GUI components

Java Lynn Lambert CPSC150

Java GUIJava GUIThe Java GUI inheritance hierarchy

ObjectObject

ColorColor

ContainerContainerComponentComponent

LayoutManagerLayoutManager

PanelPanel

WindowWindow

AppletApplet

FrameFrame

DialogDialog

JComponentJComponent

JAppletJApplet

JFrameJFrame

JDialogJDialog

lightweightlightweight

heavyweightheavyweight

Swing

AWT

Java Lynn Lambert CPSC150

Java GUIJava GUIThe Java GUI inheritance hierarchy

JComponentJComponent

JMenuBarJMenuBar

AbstractButtonAbstractButton

JScrollPaneJScrollPane

JPanelJPanel

JTextComponentJTextComponent

JLabelJLabel

JComboBoxJComboBox

JMenuItemJMenuItem

JButtonJButton

JTextAreaJTextArea

JTextFieldJTextField JPasswordFieldJPasswordField

… etc. Swing

Java Lynn Lambert CPSC150

Rest of GUIsRest of GUIs

Overview of SwingOverview of Swing JOptionPane exampleJOptionPane example

(from Dr. Flores and from Chapter 11)(from Dr. Flores and from Chapter 11) MenuBarsMenuBars

Java Lynn Lambert CPSC150

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 frameparent frame messagemessage

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

titletitle

message typemessage 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 DialogsReady-to-use Dialogs

Java Lynn Lambert CPSC150

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, -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, -1, new ImageIcon("car.gif"), options, options[1]);

parent frameparent frame

option typeoption typetitletitle

messagemessage

result value (one of):• 0…options.length-1• CLOSE_OPTION

result value (one of):• 0…options.length-1• CLOSE_OPTION

message typemessage typeiconicon

optionsoptions

selection ( options)selection ( options)

options• one label per button

options• one label per button

Ready-to-use DialogsReady-to-use Dialogs

Java Lynn Lambert CPSC150

Rest of GUIsRest of GUIs

Overview of SwingOverview of Swing JOptionPane exampleJOptionPane example MenuBars MenuBars

(from BlueJ book notes)(from BlueJ book notes)

Java Lynn Lambert CPSC150

Adding menusAdding menus

JMenuBarJMenuBar Displayed below the title.Displayed below the title. Contains the menus.Contains the menus.

JMenuJMenu e.g. e.g. FileFile. Contains the menu items.. Contains the menu items.

JMenuItemJMenuItem e.g. e.g. Open.Open. Individual items. Individual items.

Java Lynn Lambert CPSC150

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

}

Java Lynn Lambert CPSC150

Anonymous action Anonymous action listenerlistener

JMenuItem openItem = new JMenuItem("Open");

openItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); }});

Java Lynn Lambert CPSC150

Anonymous class Anonymous class elementselements

openItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { openFile(); }}

);

Anonymous object creation

Actual parameter

Class definition

Java Lynn Lambert CPSC150

Struts and GlueStruts and Glue

Invisible components used as Invisible components used as spacing.spacing.

Available from the Available from the BoxBox class. 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()

Java Lynn Lambert CPSC150

Pushing a menu to the Pushing a menu to the rightright

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)

Java Lynn Lambert CPSC150

Buttons and nested layoutsButtons and nested layouts(for information only)(for information only)

A GridLayout insidea FlowLayout insidea BorderLayout.

Java Lynn Lambert CPSC150

BordersBorders(for information only)(for information only)

Used to add decoration around Used to add decoration around components.components.

Defined in Defined in javax.swing.borderjavax.swing.border BevelBorderBevelBorder, , CompoundBorderCompoundBorder, , EmptyBorderEmptyBorder, , EtchedBorderEtchedBorder, , TitledBorderTitledBorder..

Java Lynn Lambert CPSC150

Adding spacingAdding spacing(for information only)(for information only)

JPanel contentPane = (JPanel)frame.getContentPane();contentPane.setBorder(new EmptyBorder(6, 6, 6, 6)); // Specify the layout manager with nice spacingcontentPane.setLayout(new BorderLayout(6, 6)); imagePanel = new ImagePanel();imagePanel.setBorder(new EtchedBorder());contentPane.add(imagePanel, BorderLayout.CENTER);

Java Lynn Lambert CPSC150

Other componentsOther components(for information only)(for information only)

SliderSlider SpinnerSpinner Tabbed paneTabbed pane Scroll paneScroll pane

Java Lynn Lambert CPSC150

Week 13Week 13

Rest of Guis (from Bluej web Rest of Guis (from Bluej web page)page)

mainmain

ExceptionsExceptions

Java Lynn Lambert CPSC150

mainmain

Java programs may be run outside Java programs may be run outside BlueJ (and outside of any IDE)BlueJ (and outside of any IDE)

Java programs are run on a JVMJava programs are run on a JVM Java programs run outside of blueJ Java programs run outside of blueJ

start with the method called mainstart with the method called main

Java Lynn Lambert CPSC150

Compiling Java programsCompiling Java programs

Files created in BlueJ can be run ins or Files created in BlueJ can be run ins or outside or Bluej. (Files created outside of outside or Bluej. (Files created outside of BlueJ need “Open non-BlueJ”)BlueJ need “Open non-BlueJ”)

To compile outside of Bluej, type in terminal To compile outside of Bluej, type in terminal window:window: javac nameofprogram.javajavac nameofprogram.java syntax errors will be reported in terminal windowsyntax errors will be reported in terminal window when syntax error free, .class file will be created when syntax error free, .class file will be created

(e.g., nameofprogram.java)(e.g., nameofprogram.java) NOTE: name of class MUST be the same as the NOTE: name of class MUST be the same as the

name of the file (in BlueJ and out)name of the file (in BlueJ and out)

Java Lynn Lambert CPSC150

Running Java programsRunning Java programs

To run outside of BlueJ (on JVM), type:To run outside of BlueJ (on JVM), type:java nameofprogramjava nameofprogram where nameofprogram is file name where nameofprogram is file name

except .class partexcept .class part NOT java nameofprogram.classNOT java nameofprogram.class

java nameofprogram.classjava nameofprogram.class results in the following error:results in the following error:

Exception in thread "main" Exception in thread "main" java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: nameofprogram/classnameofprogram/class

Java Lynn Lambert CPSC150

mainmain

public static void main(String[] args)public static void main(String[] args)

{{

// usually not much here. create an // usually not much here. create an object, and goobject, 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)

Java Lynn Lambert CPSC150

main method rulesmain method rules

Because it is static, all methods that Because it is static, all methods that call it must be static.call it must be static. So, don’t have many methods call itSo, don’t have many methods call it

Create an object, and go from thereCreate an object, and go from there Sometimes, especially with GUIs, no Sometimes, especially with GUIs, no

return from main. return from main. ctrl-c to end programctrl-c to end program

Java Lynn Lambert CPSC150

main examplesmain examples

All 150lab examples have mainAll 150lab examples have main compile these outsidecompile these outside run themrun them

Exercise: Create a main method for Exercise: Create a main method for your Rainfall program (program 3). your Rainfall program (program 3). Create a rainfall object in main and Create a rainfall object in main and call it. Run the program.call it. Run the program.

Java Lynn Lambert CPSC150

more on static: Math more on static: Math librarylibrary

Math library contains methods to do Math library contains methods to do mathmath log, max, sqrt, round, abs, etc.log, max, sqrt, round, abs, etc.

All methods are staticAll methods are static Why?Why?

Java Lynn Lambert CPSC150

class Myclass class Myclass {{

private double mynbr;private double mynbr;

public Myclass(double val)public Myclass(double val){{

mynbr = val;mynbr = val;}}

public double getSqrt( )public double getSqrt( ){{

return Math.sqrt(mynbr);return Math.sqrt(mynbr);

}}}}

With Math Static With Math Static methodsmethods

Java Lynn Lambert CPSC150

With Math non-static With Math non-static methodsmethodsclass Myclass class Myclass

{{private double mynbr;private double mynbr;

public Myclass(double val)public Myclass(double val){{ mynbr = val;mynbr = val; }}

public double getSqrt( )public double getSqrt( ){{

Math stupidobject = new Math( ); Math stupidobject = new Math( ); // create object in order to use sqrt method. no other // create object in order to use sqrt method. no other

reason.reason.// object is not being used. NOT like changeColor method // object is not being used. NOT like changeColor method

––// changeColor is being done on object. OR, getTitle for // changeColor is being done on object. OR, getTitle for

Item.Item.return suptidobject.sqrt(mynbr);return suptidobject.sqrt(mynbr);

}}}}

Java Lynn Lambert CPSC150

Static vs non-staticStatic vs non-static

Most methods are done for the Most methods are done for the objects. should be non-staticobjects. should be non-static

Some methods exist for the class. Some methods exist for the class. should be staticshould be static

Any methods main calls must be staticAny methods main calls must be static Lesson: main shouldn’t call many Lesson: main shouldn’t call many

methodsmethods

Java Lynn Lambert CPSC150

Week 13Week 13

Rest of Guis (from Bluej web Rest of Guis (from Bluej web page)page)mainmain

ExceptionsExceptions(from slides provided by textbook (from slides provided by textbook

web site)web site)

Java Lynn Lambert CPSC150

Handling errorsHandling errors

2.1

Java Lynn Lambert CPSC150

Some causes of error Some causes of error situationssituations

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 Inconsistent or inappropriate object state.state. E.g. arising through class extension.E.g. arising through class extension.

Java Lynn Lambert CPSC150

Not always programmer Not always programmer errorerror

Errors often arise from the Errors often arise from the environment:environment: Incorrect URL entered.Incorrect URL entered. Network interruption.Network interruption.

File processing is particular error-File processing is particular error-prone:prone: Missing files.Missing files. Lack of appropriate permissions.Lack of appropriate permissions.

Java Lynn Lambert CPSC150

Exploring errorsExploring errors

Explore error situations through the Explore error situations through the address-bookaddress-book projects. projects.

Two aspects:Two aspects: Error reporting.Error reporting. Error handling.Error handling.

Java Lynn Lambert CPSC150

Issues to be addressedIssues to be addressed

How much checking by a server on How much checking by a server on method calls?method calls?

How to report errors?How to report errors?

What if no user at the other end (e.g., What if no user at the other end (e.g., GUI)?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?

Java Lynn Lambert CPSC150

An exampleAn 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 Anticipation and prevention are

preferable to apportioning blame.preferable to apportioning blame.

Java Lynn Lambert CPSC150

Argument valuesArgument values

Arguments represent a major Arguments represent a major ‘vulnerability’ for a server object.‘vulnerability’ for a server object. Constructor arguments initialize state.Constructor arguments initialize state. Method arguments often contribute to Method arguments often contribute to

behavior.behavior. Argument checking is one defensive Argument checking is one defensive

measure.measure.

Java Lynn Lambert CPSC150

Checking the keyChecking 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--; }}

Java Lynn Lambert CPSC150

Server error reportingServer error reporting

How to report illegal How to report illegal arguments?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 valueReturn a diagnostic value

Java Lynn Lambert CPSC150

Returning a diagnosticReturning a diagnostic(Exception handling without (Exception handling without

using Java’s exception using Java’s exception handling)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; }}

Java Lynn Lambert CPSC150

Client responsesClient 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 Create something client cannot ignore: ignore: an exceptionan exception

Java Lynn Lambert CPSC150

Exception-throwing Exception-throwing principlesprinciples

Exceptions are part of many Exceptions are part of many languages, central to Java.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 Specific recovery actions are

encouraged.encouraged.

Java Lynn Lambert CPSC150

ExceptionsExceptions

Exceptions are “thrown” by the Exceptions are “thrown” by the method finding the problemmethod finding the problem

Exceptions are “caught” by the Exceptions are “caught” by the method dealing with the problemmethod dealing with the problem

maintains integrity and decouplingmaintains integrity and decoupling

Java Lynn Lambert CPSC150

Throwing an exceptionThrowing an exception

/** * Look up a name or phone number and return the * corresponding contact details. * @param key The name or number to be looked up. * @return The details corresponding to the key, * or null if there are none matching. * @throws 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); }

Java Lynn Lambert CPSC150

Throwing an exceptionThrowing 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 documentation: @throws ExceptionType reason@throws ExceptionType reason

Java Lynn Lambert CPSC150

The exception class The exception class hierarchyhierarchy

Java Lynn Lambert CPSC150

Exception categoriesException categories Checked exceptionsChecked exceptions

Subclass of Subclass of ExceptionException 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 exceptionsUnchecked exceptions Subclass of Subclass of RuntimeExceptionRuntimeException 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 Often, a programming problem (e.g., index out of

bounds)bounds) Third category: errorsThird category: errors

Java Lynn Lambert CPSC150

The effect of an The effect of an exceptionexception

The throwing method finishes The throwing method finishes prematurely.prematurely.

No return value is returned.No return value is returned. Control does not return to the Control does not return to the

client’s point of call.client’s point of call. So the client cannot carry on So the client cannot carry on

regardless.regardless. A client may ‘catch’ an exception.A client may ‘catch’ an exception.

Java Lynn Lambert CPSC150

Unchecked exceptionsUnchecked exceptions

Use of these is ‘unchecked’ by the Use of these is ‘unchecked’ by the compiler.compiler.

Cause program termination if not Cause program termination if not caught.caught. This is the normal practice.This is the normal practice.

IllegalArgumentExceptionIllegalArgumentException is a is a typical example.typical example.

Java Lynn Lambert CPSC150

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

Java Lynn Lambert CPSC150

Preventing object Preventing object creationcreationpublic 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."); }}

Java Lynn Lambert CPSC150

public class Myexceptpublic class Myexcept{{private int x;private int x;

public Myexcept()public Myexcept() { x = 0; }{ x = 0; }

public int sampleMethod(int y)public int sampleMethod(int y) {{

if (y == 0) {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; }}// …// …

Java Lynn Lambert CPSC150

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 " + System.out.println("m with 4 is " + m.sampleMethod(4));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} // end class

Java Lynn Lambert CPSC150

public static void main(String args[ ])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 System.out.println("don't call sample

method with 0");method with 0"); }} System.out.println("all done");System.out.println("all done"); } }

Java Lynn Lambert CPSC150

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

Java Lynn Lambert CPSC150

Checked ExceptionsChecked Exceptions

Previous examples all unchecked Previous examples all unchecked exceptionsexceptions unchecked exceptions should not happen; unchecked exceptions should not happen;

mostly result in program terminationmostly result in program termination Checked exceptions are meant to be Checked exceptions are meant to be

caught.caught. The compiler ensures that their use is The compiler ensures that their use is

tightly controlled.tightly controlled. In both server and client.In both server and client.

Used properly, failures may be recoverable.Used properly, failures may be recoverable.

Java Lynn Lambert CPSC150

Some Checked Some Checked ExceptionsExceptions

ClassNotFoundExceptionClassNotFoundException IOExceptionIOException NoSuchFieldExceptionNoSuchFieldException ServerNotActiveExceptionServerNotActiveException UnsupportedFlavorExceptionUnsupportedFlavorException

Java Lynn Lambert CPSC150

The throws clauseThe throws clause

Methods throwing a checked Methods throwing a checked exception must include a throws exception must include a throws clause:clause:

public void saveToFile(String destinationFile)public void saveToFile(String destinationFile) throws IOExceptionthrows IOException

(NOT throw) throw is when the (NOT throw) throw is when the exception is thrownexception is thrown

Java Lynn Lambert CPSC150

throwsthrows

must include throws in methods that must include throws in methods that throw checked exceptionsthrow checked exceptions

how do I know?how do I know? javadoc/syntax errorsjavadoc/syntax errors

Java Lynn Lambert CPSC150

The try statementThe try statement

Clients catching an exception must Clients catching an exception must protect the call with a try statement:protect the call with a try statement:

try {try { Protect one or more statements here.Protect one or more statements here.}}catch(Exception e) {catch(Exception e) { Report and recover from the exception here.Report and recover from the exception here.}}

Java Lynn Lambert CPSC150

The try statementThe 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

Java Lynn Lambert CPSC150

Catching multiple Catching multiple exceptionsexceptions

try in order that they try in order that they appearappear

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

Java Lynn Lambert CPSC150

The finally clauseThe 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.}

Java Lynn Lambert CPSC150

The finally clauseThe finally clause

A finally clause is executed even if a A finally clause is executed even if a return statement is executed in the return statement is executed in the try or catch clauses.try or catch clauses.

A uncaught or propagated exception A uncaught or propagated exception still exits via the finally clause.still exits via the finally clause.

Java Lynn Lambert CPSC150

Error recoveryError recovery

Clients should take note of error Clients should take note of error notifications.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.

Java Lynn Lambert CPSC150

Attempting recoveryAttempting 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;}

Java Lynn Lambert CPSC150

Error avoidanceError avoidance

Clients can often use server query Clients can often use server query methods to avoid errors.methods to avoid errors. More robust clients mean servers can More robust clients mean servers can

be more trusting.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.

Java Lynn Lambert CPSC150

FilesFiles

Chapter 12 continuedChapter 12 continued

Java Lynn Lambert CPSC150

Text input-output:Text input-output:tie to exceptionstie to exceptions

Input-output is particularly error-Input-output is particularly error-prone.prone. It involves interaction with the external It involves interaction with the external

environment.environment. The The java.iojava.io package supports package supports

input-output.input-output. java.io.IOExceptionjava.io.IOException is a checked is a checked

exception.exception. cannot do files without exceptionscannot do files without exceptions

Java Lynn Lambert CPSC150

FilesFiles

To use files, use File classTo use files, use File class File class can’t read/writeFile class can’t read/write To read/write files, use To read/write files, use

Reader/Writer classesReader/Writer classes File input can be text-based (what File input can be text-based (what

we’ll do), stream-basedwe’ll do), stream-based

Java Lynn Lambert CPSC150

Readers, writers, streamsReaders, writers, streams

Readers and writers deal with Readers and writers deal with textual input.textual input. Based around the Based around the charchar type. type.

Streams deal with binary data.Streams deal with binary data. Based around the Based around the bytebyte type. type.

The The address-book-ioaddress-book-io project project illustrates textual IO.illustrates textual IO.

Java Lynn Lambert CPSC150

Text outputText output

Use the Use the FileWriterFileWriter class. class. Tie File object to diskfile nameTie 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 Failure at any point results in an IOExceptionIOException..

Java Lynn Lambert CPSC150

Text outputText 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}

Java Lynn Lambert CPSC150

Text inputText input

Use the Use the FileReaderFileReader class. class. Augment with Augment with BufferedReaderBufferedReader for for

line-based input.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 Failure at any point results in an IOExceptionIOException..

Java Lynn Lambert CPSC150

Text inputText 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}

Java Lynn Lambert CPSC150

Write a program to count Write a program to count number of lines in a file and number of lines in a file and

write the number to an write the number to an output fileoutput file

java countlines myinfile.txt java countlines myinfile.txt myoutfile.txtmyoutfile.txt

would return 2 if file is:would return 2 if file is:This is a file

with two lines.

myinfile.txt

Java Lynn Lambert CPSC150

import java.io.*;import java.io.*;

public class countlinespublic class countlines{{

// all methods that do something inserted here// 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 System.out.println("to run, type: 'countlines filein

fileout'");fileout'"); System.exit(1);System.exit(1); }}// create a new countline object with first arg as input file, // create a new countline object with first arg as input file,

second as outputsecond as output countlines cl = new countlines(args[0], args[1]);countlines cl = new countlines(args[0], args[1]);

}}}}

Java Lynn Lambert CPSC150

// constructor// constructorpublic countlines(String filein, String fileout) 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 // will catch any IO exception not caught by

readfrom and writetoreadfrom and writeto System.out.println("Problems with IO. System.out.println("Problems with IO.

Program aborted without successful Program aborted without successful write.");write.");

}} }}

Java Lynn Lambert CPSC150

// file output. method called from constructor// file output. method called from constructorpublic void writeto(String fileout, int nbrlines) public void writeto(String fileout, int nbrlines)

throws IOExceptionthrows IOException// // must have “throws IOException” even though must have “throws IOException” even though // // no “throw statement”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 fw.write("There were " + nbrlines + " lines

in the input file.");in the input file."); fw.close();fw.close(); }}

Java Lynn Lambert CPSC150

public int readfrom(String filename) throws IOExceptionpublic 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 BufferedReader reader = new BufferedReader(new

FileReader(infile));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; }}

Java Lynn Lambert CPSC150

Other WrappersOther Wrappers

Can break string read up using Can break string read up using StringTokenizerStringTokenizer

Can read non-text files with Can read non-text files with FileReader and Tokenizer (breaks FileReader and Tokenizer (breaks fields up to be read)fields up to be read)