Top Banner
UCSC 2003. All rights reserved.No parts of this material IT1202-Fundamentals Of Programming (Using JAVA) Streams & Error Handling in Java Version 1.0
48

Streams and Error Handling in Java

Jun 03, 2018

Download

Documents

Anupamn
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 1/48

UCSC 2003. All rightsreserved.No parts of this material

IT1202-Fundamentals Of Programming

(Using JAVA)Streams & Error Handling in Java

Version 1.0

Page 2: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 2/48

UCSC 2003. All rightsreserved.No parts of this material

Input & output

• Most real applications of Java are not textbased, console programs. Rather they are

graphically oriented applets that rely upon

Java’s Abstract Window Toolkit (AWT) for

interactions with the user.

• Java support string flexible support for I/O

as it relates to files and network .

• Java’s I/O system is cohesive andconsistent.

Page 3: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 3/48

UCSC 2003. All rightsreserved.No parts of this material

Using command line arguments

• As you know Java applications arestandalone programs, so, it’s useful topass arguments or options to anapplication.

• Arguments can be used to determine howthe application is going to run.

OR

• Enable a generic application to operate on

different kinds of input.• Using program arguments can,

 – Turn on debugging input.

 – Indicate a filename to load.

Page 4: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 4/48

UCSC 2003. All rightsreserved.No parts of this material

• This caries based on the platform you’re

running.• On Windows & UNIX can use command line.

• To pass arguments to a Java program onWindows or Solaris, the arguments should

be appended to the command line when

the program is run.eg:

Java MyProg ram argum entOne 2 three

In th ee three arguments w ere passed to a prog ram.

argumentOne, the number 2 & th ree. Note that a space

Separates each of th e arguments.

Passing Arguments to Java Applications

Page 5: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 5/48

UCSC 2003. All rightsreserved.No parts of this material

Passing Arguments to Java Applications….. 

• To group arguments that include spaces,the arguments should be surrounded with

“ ” marks. 

• These quotation marks are not included in

the argument when it is sent to theprogram & received using the main()

method.

Page 6: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 6/48

UCSC 2003. All rightsreserved.No parts of this material

• When an application is run with arguments,

Java stores the arguments as an array of as

strings & passes the array to the application’s

main() method.eg:

pub l ic static v oid m ain(Str ing arguments[ ] ) {

 // body o f method

 }In here, arguments  is the name of the array o f str ing s that

con tains l is t of arguments .

Handling Arguments in Java Application

Page 7: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 7/48

UCSC 2003. All rightsreserved.No parts of this material

Handling Arguments in Java Application… 

• Inside the main() method, you can handle thearguments your program was given, – By iterating.

And

 – Handling them in some manner.eg:

class EchoA rgs {

publ ic stat ic vo id main (Str ing arguments[]) {

for (int i=0; i<argum ents .length ; i++) {

System.out.println(“Argument” + i + “:” +arguments [ i ] );

 }

 }

 }

Page 8: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 8/48

UCSC 2003. All rightsreserved.No parts of this material

• Eg: – Input

 java EchoArgs Wilhelm Niekro Hough 49

 – Output

Argument 0: Wi lhelmArgument 1: Niekro

Argument 2: Hough

Arg ument 3: 49

Handling Arguments in Java Application… 

Page 9: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 9/48

UCSC 2003. All rightsreserved.No parts of this material

• All arguments passed to a Javaapplication are stored in an array ofstrings.

• To treat them as something other than

strings, you must convert them.• The following program takes any number of

numeric arguments & returns the sum & theaverage of those arguments.class SumAverage {

publ ic stat ic void m ain(Str ing args[]) {

in t sum = 0;

for (int I = 0; i<args .length ; i++) {

Sum += args[ i ] ;

 }

Handling Arguments in Java Application… 

Page 10: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 10/48

UCSC 2003. All rightsreserved.No parts of this material

System.out.println(“Sum is;” + sum); System.out.println(“Average is:” + 

(float) sum / args.length );

 }

 }

Output

SumAverage.java.6: Incompatible type for +=. Can’t convert  

 java.lang .Str ing to in t.

Sum += args[ i ] ;

• This error occurs the argument array is an array

of strings.

Handling Arguments in Java Application… 

Page 11: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 11/48

UCSC 2003. All rightsreserved.No parts of this material

•  You have to convert them from strings tointegers using a class method for the

Integer  class called parseInt.Sum += Integer.parseInt(args[i ]) ;

• By applying the following inputs to theexample we can run the program.

• InputJava SumAverage 123

• OutputSum is : 6

Av erage is : 2

Handling Arguments in Java Application… 

Page 12: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 12/48

UCSC 2003. All rightsreserved.No parts of this material

Streams: input stream, output stream &

error stream

• Is a path of communication between asource of some information anddestination

• The source can be a file, computersmemory or the Internet

• Input Streams  sends data from a sourceinto a program

• ou tput st reams  sends data out of aprogram to a destination

Page 13: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 13/48

UCSC 2003. All rightsreserved.No parts of this material

• Java programs perform I/O through streams.

• A stream is a path of communication between asource of some information and destination and astream is linked to a physical device by the JavaI/O system.

• The source can be a file, computers memory orthe Internet.

• All streams behave in the same manner, even ifthe actual physical devices to which they arelinked differ.

• Input Streams allows you to read data from asource

• output streams allows you to write data to adestination

Streams……… 

Page 14: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 14/48

UCSC 2003. All rightsreserved.No parts of this material

• Byte streams and character streams – Java 2 defines two types of streams: Byte and

Character.

 – Byte streams

• Byte streams provide a convenient meansfor handling input and output of bytes.

• Byte streams are used when reading orwriting binary data.

-Character streams

• Character streams provide a convenientmeans for handling input and output ofcharacters.

• They are unicode and therefore, can be

internationalized.

Streams……… 

Page 15: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 15/48

UCSC 2003. All rightsreserved.No parts of this material

• Using a Stream

 – Whether you’re using a byte stream or acharacter stream, the procedure forusing either in Java is largely the same.

 – For an input stream, the first step is tocreate an object that is associated withthe data source.

 – After you have created a stream object,

you can read information from thatstream by using one of the object’smethods. FileInputStream includes aread() method that returns a byte read

from the file.

Streams……… 

Page 16: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 16/48

UCSC 2003. All rightsreserved.No parts of this material

Using a Stream………. 

• When you’re done reading information

from the stream, you call the close()method to indicate that you’re done usingthe stream.

• For an output stream, you begin by

creating an object that’s associated withthe data’s destination. BufferedReaderclass can be used to create such text files.

• The write() method is the simplest method

to send information to the output stream’sdestination.

• A BufferedReader write() method can sendindividual characters to an output stream.

Page 17: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 17/48

UCSC 2003. All rightsreserved.No parts of this material

Using a Stream……….. 

• The close() is called on an output streamwhen you have no more information to

send.

Page 18: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 18/48

UCSC 2003. All rightsreserved.No parts of this material

Filtering a Stream

• A filter is a type of stream that modifiesthe way an existing stream is handled.

• The procedure for using a filter on a

stream is basically as follows.

 – Create a stream associated with a data source

or a data destination.

 – Associate a filter with that stream.

 – Read or write data from the filter rather than

the original stream.

• The methods you call on a filter are,

 – read()

 – write()

Page 19: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 19/48

UCSC 2003. All rightsreserved.No parts of this material

• A filter can associate with another filter.

Filtering a Stream……….. 

Page 20: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 20/48

UCSC 2003. All rightsreserved.No parts of this material

The predefined Stream

•  All Java programs automatically import theJava.lang package.

• This package defines a class called System,

which encapsulates severl aspects of the run-

time environment. E.g. current time and

settings of various properties associated with

the system.

• System also contains three predefined stream

variables ,in, out and err.

Page 21: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 21/48

UCSC 2003. All rightsreserved.No parts of this material

Reading Console Input

• In Java1.0, the only way to perform consoleinput was to use a byte stream.

• The predefined method of reading console inputfor Java2 is to use a character- oriented stream.

• In Java, console input is accomplished byreading from System.in.

• To obtain a character- based stream that isattached to the console, you wrap system.in in a

BuffrerdReader object.

Page 22: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 22/48

UCSC 2003. All rightsreserved.No parts of this material

Byte stream

• All byte streams are either a subclass of – InputStream

OR

 – OutputStream

• These classes are abstract.• Instead you can create through one of

their subclasses. – FileInputStream & Fi leOutpu tStream

By te streams s tored in f i les on d isk, CD-ROM or othersto rage devices.

 – DataInputStream & DataOutpu tStream

A f i ltered by te stream from wh ich data such as

integers &

Float ing-point numbers can be read.

Page 23: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 23/48

UCSC 2003. All rightsreserved.No parts of this material

• File Streams – These are used to exchange data with files on

your disk drives, CD-ROMs or other storage

devices.

 –  You can send bytes to a file output stream &receive bytes from a file input stream.

Byte stream………. 

Page 24: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 24/48

UCSC 2003. All rightsreserved.No parts of this material

• File Input Streams

 – A file input stream can be created withthe FileInputStream(String) constructor.

 – The string argument should be the

name of the file. – The following statement creates a file

input stream from the file scores.dat.FileInp utStream fis = new

FileInputStream(“scores.dat”); 

 – After you create a file input stream, youcan read bytes from the stream bycalling its read() method.

Byte stream………. 

Page 25: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 25/48

UCSC 2003. All rightsreserved.No parts of this material

• To read more than one byte of data fromthe stream, call its read(byte[], int, int)

method.

Byte stream………. 

Page 26: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 26/48

UCSC 2003. All rightsreserved.No parts of this material

• File Output Streams – A file output stream can be created with the

FileOutputStream(String) constructor.

 –  You can create a file output stream that

appends data after the end of an existing filewith the FileOutputStream(String, boolean)

constructor.

 – The file output stream’s write(int) method is

used to write bytes to the stream.

 – To write more than one byte, the

write(byte[],int,int) method can be used. 

Byte stream………. 

Page 27: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 27/48

UCSC 2003. All rightsreserved.No parts of this material

Data Streams

• When you need to work with data that isn’trepresented as bytes or characters, youcan use data input & data output streams.

• These streams filter an existing byte

stream so that each of the followingprimitive types can be read or writtendirectly from the stream:boolean, byte, double, float, int, long & short

• A data input stream is created with theDataInputStream(InputStream)constructor.

Page 28: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 28/48

UCSC 2003. All rightsreserved.No parts of this material

• A data output stream requires theDataOutputStream(OutputStream)

constructor which indicates the

associated output stream.

Data Streams……… 

Page 29: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 29/48

UCSC 2003. All rightsreserved.No parts of this material

Input and Output

• Reading Characters. – To read a character from a BufferedReader, use read().

 – Each time read() is called it reds a character from theinput stream and returns it as an integer value.

• Readong Strings – To read a string from the keyboard use readline() that i

a member of the BuffreredReader class.

•   Writing Console Output –   Console output is most easily accomplished with

print() and println().

Page 30: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 30/48

UCSC 2003. All rightsreserved.No parts of this material

Input and Output

 – These methods are defined by the classPrintStream.

 – PrintStream implements the low-level

method write().

 – You will not use write() to perform sonsole

output (although doing so might be usefu

in some situations), because print() and

println() are subtantially easier to use.

Page 31: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 31/48

UCSC 2003. All rightsreserved.No parts of this material

Input and Output

• The PrintWriter class – System.out is recommended mostly for debugging

purposes or sample programs, for real-worldprograms, the recommended method of writing tothe console when using Java is through a

PrintWriter atream. – Printwriter is one of the character- based classes.

 – PrintWriter supports the print() and println()methods for all types including object. Thus youcan use these methods in the same way as theyhave been used with system.out.

Page 32: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 32/48

UCSC 2003. All rightsreserved.No parts of this material

Input and Output

• Reading and writing files – Java provides a no. of classes and methods that

allow you to read and write files.

 – In java, all files are byte-oriented and java

provides methods to read and write byte fromand to a file.

 – Java allows you to wrap a byte-oriented filesystem within a character-based object.

 – Two of the most-often used stream classes are

FileInputStream and FileOutputStream, whichcreate byte streams linked to files.

Page 33: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 33/48

UCSC 2003. All rightsreserved.No parts of this material

Input and Output

• Creating an input file:-FileInputStream (String f i leName ) throwsFileNotFoundExeption

• Opening an output file:-FileOutputStream (String f i leName ) throwsFileNotFoundExeption

• Closing a file:-Void close() throws IOException

• Read from a fileVoid write(int byteval) throws IOException

This method writes the byte specified by the byteval to the file.

Page 34: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 34/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling• A Java Exception is an object that

describes an exceptional (that is, error)condition that has occurred in a piece ofcode.

• Exceptions can be generated by the Java

run-time system, or they can e manuallygenerated by your code.

• Exceptions thrown by Java relate tofundamental errors that violate the rules of

the Java language or the constraints ofthe Java execution environment. 

Page 35: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 35/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

 java .lang.Object

 java .lang.Throwable

 java .lang.Exception

IOException

RuntimeException

Java Exception

class hierarchy

Page 36: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 36/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

• Handling Exceptions – In many cases Java Compiler enforces

Exception Management when methods

that throw exceptions are used

 – it is necessary to handle those

exceptions within the code, or that code

will not compile at all

Page 37: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 37/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

• Protecting code and catching Exceptions – To catch an Exception,

• Although the default exception handler provided by the Javarun-time system is useful for debugging, you will usually wantto handle an exception by your self.

• To guard against and handle a runtime error, protect your codethat contains an exception throwable method within a t ry  block

• Test and deal with the exception within a catch  block

Page 38: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 38/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

Class DivideZero {

static int anyFunction (int x, int y) {

try {

int a = x / y;return a;

}

catch (ArithmeticException e) {

System.out.println(“Division by Zero “); 

}

}

Code is protectedusing try Block

Exception is caught and handled

using catch block

Page 39: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 39/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

• Displaying a description of an exception

 – Throwable overrides the toString() . So it

returns a string containing a description ofthe exception.

 – E.g.catch (ArithmeticException e) {

System.out.println(“Exception : “+e); 

}Exception is passed as an argument in a println() statement

Page 40: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 40/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

• Multiple catch Clauses – When more than one exception is raised

by a single piece of code you canspecify two or more catch clauses, each

catching a different type of exception . – When you use multiple catch

statements , exception subclasses mustcome before any of there superclasses.

Page 41: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 41/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

• Nested Try Statements

 – The try statement can be nested.

 – Each time a try statement is entered ,the context of that exception is pushedon the stack.

 – Nesting of try statements can occur in

less obvious ways when method callsare involved.

Page 42: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 42/48

UCSC 2003. All rightsreserved.No parts of this material

Error Handling Contd...

• Throw clause – It is possible for your program to throw an exception

using throw statement .

Throw ThrowableInstance  ThrowableInstance must be an object of type Throwable or a

subclass of Throwable.

Simple types, such as int or char, as well as non-Throwable

classes such as String and Obiect cannot be used as

exceptions.

Page 43: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 43/48

UCSC 2003. All rights

reserved.No parts of this material

Error Handling Contd...

• finally  clause

 – If there is a piece of code that should be

executed whether an exception occurs

or not then• include it within the optional f inal ly  clause

of the try..catch block

• an example may be closing an open file.

Page 44: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 44/48

UCSC 2003. All rights

reserved.No parts of this material

Error Handling Contd...

• throws clause – used to indicate that a method will throw an

exception.

 – Used after the signature of a method (beforethe opening curly bracket)

 – if multiple Exceptions are thrown, include them

in throws clause separated by commas.

Public myMethod (int x, int y) throws Exception1,Exceptio

{

Page 45: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 45/48

UCSC 2003. All rights

reserved.No parts of this material

Error Handling Contd...

• throws clause contd… 

 – this clause also may be included in a

method that throws an exception which

you do not intend to do anything about.

 – It makes sense that the method that

calls your method should handle the

exception in its code , not within yourmethod.

Page 46: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 46/48

UCSC 2003. All rights

reserved.No parts of this material

Error Handling Contd...

• Java’s built –in Exceptions – Inside the standard package Java.lang, java defines

several exception classes.

 – The most general of these exceptions are subclassesof the standard tye RuntimeException.

 – As Java.lang is implicitly imported in to all Java

programs, most exceptions derived from

RuntimeException are automatically available; theyneed not be included in a method’s throw list.

Error Handling Contd

Page 47: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 47/48

UCSC 2003. All rights

reserved.No parts of this material

Error Handling Contd...

• Defining and Generating Exceptions… 

 –  You can define your own exceptions and throwthem as you would throw any standard exception.

 – First You need to define a new exception class

• it should be a sub class of class throwable or any sub

class of throwable. – Create a new Object of the defined class using

new and throw it

Error Handling Contd

Page 48: Streams and Error Handling in Java

8/12/2019 Streams and Error Handling in Java

http://slidepdf.com/reader/full/streams-and-error-handling-in-java 48/48

UCSC 2003 All rights

Error Handling Contd...public class SunSpotException

extends Exception {public SunSpotException() {}

public SunSpotExceotion(String msg) {

super(msg);

}}

Throw new SunSpotException ( );OR

throw new SunSpotException (“This is

to test”); 

Defining Exception