Download - 7 streams and error handling in java

Transcript
Page 1: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

IT1202-Fundamentals Of Programming(Using JAVA)

Streams & Error Handling in JavaVersion 1.0

Page 2: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Input & output• Most real applications of Java are not text

based, 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 and consistent.

Page 3: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Using command line arguments

• As you know Java applications are standalone programs, so, it’s useful to pass arguments or options to an application.

• Arguments can be used to determine how the 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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• This caries based on the platform you’re running.

• On Windows & UNIX can use command line.

• To pass arguments to a Java program on Windows or Solaris, the arguments should be appended to the command line when the program is run.

eg:Java MyProgram argumentOne 2 three

In thee three arguments were passed to a program.argumentOne, the number 2 & three. Note that a space Separates each of the arguments.

Passing Arguments to Java Applications

Page 5: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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 the program & received using the main() method.

Page 6: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• 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:

public static void main(String arguments[]) {// body of method

}In here, arguments is the name of the array of strings thatcontains list of arguments.

Handling Arguments in Java Application

Page 7: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Handling Arguments in Java Application…

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

And– Handling them in some manner.eg:

class EchoArgs {public static void main (String arguments[]) {

for (int i=0; i<arguments.length; i++) {System.out.println(“Argument” + i + “:” +

arguments [i]);}

}}

Page 8: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• Eg:– Input

java EchoArgs Wilhelm Niekro Hough 49– Output

Argument 0: WilhelmArgument 1: NiekroArgument 2: HoughArgument 3: 49

Handling Arguments in Java Application…

Page 9: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• All arguments passed to a Java application are stored in an array of strings.

• To treat them as something other than strings, you must convert them.

• The following program takes any number of numeric arguments & returns the sum & the average of those arguments.class SumAverage {

public static void main(String args[]) {int sum = 0;for (int I = 0; i<args.length; i++) {

Sum += args[i];}

Handling Arguments in Java Application…

Page 10: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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

(float) sum / args.length);}

}

OutputSumAverage.java.6: Incompatible type for +=. Can’t convertjava.lang.String to int.Sum += args[i];

• This error occurs the argument array is an array of strings.

Handling Arguments in Java Application…

Page 11: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• You have to convert them from strings to integers using a class method for the Integer class called parseInt.Sum += Integer.parseInt(args[i]);

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

• InputJava SumAverage 123

• OutputSum is : 6Average is : 2

Handling Arguments in Java Application…

Page 12: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Streams: input stream, output stream & error stream

• Is a path of communication between a source of some information and destination

• The source can be a file, computers memory or the Internet

• Input Streams sends data from a source into a program

• output streams sends data out of a program to a destination

Page 13: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• Java programs perform I/O through streams.• A stream is a path of communication between a

source of some information and destination and a stream is linked to a physical device by the Java I/O system.

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

• All streams behave in the same manner, even if the actual physical devices to which they are linked differ.

• Input Streams allows you to read data from a source

• output streams allows you to write data to a destination

Streams………

Page 14: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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

Character.– Byte streams

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

• Byte streams are used when reading or writing binary data.

-Character streams• Character streams provide a convenient means

for handling input and output of characters.• They are unicode and therefore, can be

internationalized.

Streams………

Page 15: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• Using a Stream– Whether you’re using a byte stream or a

character stream, the procedure for using either in Java is largely the same.

– For an input stream, the first step is to create an object that is associated with the data source.

– After you have created a stream object, you can read information from that stream by using one of the object’s methods. FileInputStream includes a read() method that returns a byte read from the file.

Streams………

Page 16: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Using a Stream……….

• When you’re done reading information from the stream, you call the close() method to indicate that you’re done using the stream.

• For an output stream, you begin by creating an object that’s associated with the data’s destination. BufferedReader class can be used to create such text files.

• The write() method is the simplest method to send information to the output stream’s destination.

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

Page 17: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Using a Stream………..

• The close() is called on an output stream when you have no more information to send.

Page 18: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Filtering a Stream• A filter is a type of stream that modifies

the 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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• A filter can associate with another filter.

Filtering a Stream………..

Page 20: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

The predefined Stream• All Java programs automatically import the

Java.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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Reading Console Input • In Java1.0, the only way to perform console

input was to use a byte stream.• The predefined method of reading console input

for Java2 is to use a character- oriented stream. • In Java, console input is accomplished by

reading from System.in.• To obtain a character- based stream that is

attached to the console, you wrap system.in in a BuffrerdReader object.

Page 22: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Byte stream• All byte streams are either a subclass of

– InputStreamOR

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

subclasses.– FileInputStream & FileOutputStream

Byte streams stored in files on disk, CD-ROM or otherstorage devices.

– DataInputStream & DataOutputStreamA filtered byte stream from which data such as integers &Floating-point numbers can be read.

Page 23: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• 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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• File Input Streams– A file input stream can be created with

the 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.FileInputStream fis = new

FileInputStream(“scores.dat”);– After you create a file input stream, you

can read bytes from the stream by calling its read() method.

Byte stream……….

Page 25: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• To read more than one byte of data from the stream, call its read(byte[], int, int) method.

Byte stream……….

Page 26: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• 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 file with 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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Data Streams• When you need to work with data that isn’t

represented as bytes or characters, you can use data input & data output streams.

• These streams filter an existing byte stream so that each of the following primitive types can be read or written directly from the stream:boolean, byte, double, float, int, long & short

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

Page 28: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

• A data output stream requires the DataOutputStream(OutputStream) constructor which indicates the associated output stream.

Data Streams………

Page 29: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Input and Output• Reading Characters.

– To read a character from a BufferedReader, use read().– Each time read() is called it reds a character from the input stream

and returns it as an integer value.

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

of the BuffreredReader class.

• Writing Console Output– Console output is most easily accomplished with print() and

println().

Page 30: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Input and Output– These methods are defined by the class

PrintStream.– 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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Input and Output• The PrintWriter class

– System.out is recommended mostly for debugging purposes or sample programs, for real-world programs, the recommended method of writing to the 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 you can use these methods in the same way as they have been used with system.out.

Page 32: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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 from and to a file.

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

– Two of the most-often used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files.

Page 33: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Input and Output• Creating an input file:-

FileInputStream (String fileName ) throws FileNotFoundExeption

• Opening an output file:- FileOutputStream (String fileName ) throws

FileNotFoundExeption• Closing a file:-

Void close() throws IOException• Read from a file

Void write(int byteval) throws IOExceptionThis method writes the byte specified by the byteval to the file.

Page 34: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling• A Java Exception is an object that

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

• Exceptions can be generated by the Java run-time system, or they can e manually generated by your code.

• Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.

Page 35: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...

java .lang.Object

java .lang.Throwable

java .lang.Exception

IOException

RuntimeException

Java Exceptionclass hierarchy

Page 36: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...• Protecting code and catching Exceptions

– To catch an Exception,• Although the default exception handler provided by the Java

run-time system is useful for debugging, you will usually want to handle an exception by your self.

• To guard against and handle a runtime error, protect your code that contains an exception throwable method within a try block

• Test and deal with the exception within a catch block

Page 38: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...

• Displaying a description of an exception

– Throwable overrides the toString() . So it returns a string containing a description of the exception.

– E.g. catch (ArithmeticException e) {

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

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

Page 40: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...• Multiple catch Clauses

– When more than one exception is raised by a single piece of code you can specify two or more catch clauses, each catching a different type of exception .

– When you use multiple catch statements , exception subclasses must come before any of there superclasses.

Page 41: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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 pushed on the stack.

– Nesting of try statements can occur in less obvious ways when method calls are involved.

Page 42: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...• Throw clause

– It is possible for your program to throw an exception using throw statement .

Throw ThrowableInstanceThrowableInstance 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: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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 finally clause of the try..catch block

• an example may be closing an open file.

Page 44: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...

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

exception.– Used after the signature of a method (before

the opening curly bracket)– if multiple Exceptions are thrown, include them

in throws clause separated by commas.

Public myMethod (int x, int y) throws Exception1,Exception2{

Page 45: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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

Page 46: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

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 subclasses of the standard tye RuntimeException.

– As Java.lang is implicitly imported in to all Java programs, most exceptions derived from RuntimeException are automatically available; they need not be included in a method’s throw list.

Page 47: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...• Defining and Generating Exceptions…

– You can define your own exceptions and throw them 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

Page 48: 7 streams and error handling in java

UCSC 2003. All rights reserved.No parts of this material may be reproduced and sold.

Error Handling Contd...public class SunSpotException

extends Exception { public SunSpotException() {} public SunSpotExceotion(String msg) { super(msg); }}

Throw new SunSpotException ( );ORthrow new SunSpotException (“This is

to test”);

Defining Exception

Throwing