SlideShare uma empresa Scribd logo
1 de 48
UCSC 2003. All rights reserved.No parts of this material may be reproduced and so
IT1202-Fundamentals Of Programming
(Using JAVA)
Streams & Error Handling in Java
Version 1.0
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
• 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
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
• 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 that
contains list of arguments.
Handling Arguments in Java Application
UCSC 2003. All rights reserved.No parts of this material ma
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]);
}
}
}
UCSC 2003. All rights reserved.No parts of this material ma
• Eg:
– Input
java EchoArgs Wilhelm Niekro Hough 49
– Output
Argument 0: Wilhelm
Argument 1: Niekro
Argument 2: Hough
Argument 3: 49
Handling Arguments in Java Application…
UCSC 2003. All rights reserved.No parts of this material ma
• 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…
UCSC 2003. All rights reserved.No parts of this material ma
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.String to int.
Sum += args[i];
• This error occurs the argument array is an array
of strings.
Handling Arguments in Java Application…
UCSC 2003. All rights reserved.No parts of this material ma
• 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.
• Input
Java SumAverage 123
• Output
Sum is : 6
Average is : 2
Handling Arguments in Java Application…
UCSC 2003. All rights reserved.No parts of this material ma
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
UCSC 2003. All rights reserved.No parts of this material ma
• 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………
UCSC 2003. All rights reserved.No parts of this material ma
• 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………
UCSC 2003. All rights reserved.No parts of this material ma
• 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………
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
Using a Stream………..
• The close() is called on an output stream
when you have no more information to
send.
UCSC 2003. All rights reserved.No parts of this material ma
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()
UCSC 2003. All rights reserved.No parts of this material ma
• A filter can associate with another filter.
Filtering a Stream………..
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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 & FileOutputStream
Byte streams stored in files on disk, CD-ROM or other
storage devices.
– DataInputStream & DataOutputStream
A filtered byte stream from which data such as
integers &
Floating-point numbers can be read.
UCSC 2003. All rights reserved.No parts of this material ma
• 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……….
UCSC 2003. All rights reserved.No parts of this material ma
• 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……….
UCSC 2003. All rights reserved.No parts of this material ma
• To read more than one byte of data from
the stream, call its read(byte[], int, int)
method.
Byte stream……….
UCSC 2003. All rights reserved.No parts of this material ma
• 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……….
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
• A data output stream requires the
DataOutputStream(OutputStream)
constructor which indicates the
associated output stream.
Data Streams………
UCSC 2003. All rights reserved.No parts of this material ma
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().
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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 IOException
This method writes the byte specified by the byteval to the file.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
Error Handling Contd...
java .lang.Object
java .lang.Throwable
java .lang.Exception
IOException
RuntimeException
Java Exception
class hierarchy
UCSC 2003. All rights reserved.No parts of this material ma
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
UCSC 2003. All rights reserved.No parts of this material ma
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
UCSC 2003. All rights reserved.No parts of this material ma
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 protected
using try Block
Exception is caught and handled
using catch block
UCSC 2003. All rights reserved.No parts of this material ma
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
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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,Exception
{
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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.
UCSC 2003. All rights reserved.No parts of this material ma
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
UCSC 2003. All rights reserved.No parts of this material ma
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
Throwing

Mais conteúdo relacionado

Mais procurados

Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
IO In Java
IO In JavaIO In Java
IO In Javaparag
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1ashishspace
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streamsbabak danyal
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 

Mais procurados (20)

Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
14 file handling
14 file handling14 file handling
14 file handling
 
Java stream
Java streamJava stream
Java stream
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
IO In Java
IO In JavaIO In Java
IO In Java
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
Files in java
Files in javaFiles in java
Files in java
 
15. text files
15. text files15. text files
15. text files
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Basic of java
Basic of javaBasic of java
Basic of java
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 

Destaque

[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingChristina Lin
 
Improve business process with microservice integration
Improve business process with microservice integration �Improve business process with microservice integration �
Improve business process with microservice integration Christina Lin
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 

Destaque (8)

14 hql
14 hql14 hql
14 hql
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error Handling
 
Improve business process with microservice integration
Improve business process with microservice integration �Improve business process with microservice integration �
Improve business process with microservice integration
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 

Semelhante a 7 streams and error handling in java

Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxnoonoboom
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptxssuser9d7049
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptxYashrajMohrir
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptxRathanMB
 
Java SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).pptJava SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).pptAayush Chimaniya
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals WebStackAcademy
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2Gera Paulos
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsKuntal Bhowmick
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsKuntal Bhowmick
 
Java platform
Java platformJava platform
Java platformVisithan
 

Semelhante a 7 streams and error handling in java (20)

Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
JAVA (UNIT 3)
JAVA (UNIT 3)JAVA (UNIT 3)
JAVA (UNIT 3)
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Java I/O
Java I/OJava I/O
Java I/O
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
Java 8
Java 8Java 8
Java 8
 
Java SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).pptJava SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).ppt
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
 
Java platform
Java platformJava platform
Java platform
 

Último

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Último (20)

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

7 streams and error handling in java

  • 1. UCSC 2003. All rights reserved.No parts of this material may be reproduced and so IT1202-Fundamentals Of Programming (Using JAVA) Streams & Error Handling in Java Version 1.0
  • 2. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 3. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 4. UCSC 2003. All rights reserved.No parts of this material ma • 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
  • 5. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 6. UCSC 2003. All rights reserved.No parts of this material ma • 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 that contains list of arguments. Handling Arguments in Java Application
  • 7. UCSC 2003. All rights reserved.No parts of this material ma 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]); } } }
  • 8. UCSC 2003. All rights reserved.No parts of this material ma • Eg: – Input java EchoArgs Wilhelm Niekro Hough 49 – Output Argument 0: Wilhelm Argument 1: Niekro Argument 2: Hough Argument 3: 49 Handling Arguments in Java Application…
  • 9. UCSC 2003. All rights reserved.No parts of this material ma • 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…
  • 10. UCSC 2003. All rights reserved.No parts of this material ma 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.String to int. Sum += args[i]; • This error occurs the argument array is an array of strings. Handling Arguments in Java Application…
  • 11. UCSC 2003. All rights reserved.No parts of this material ma • 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. • Input Java SumAverage 123 • Output Sum is : 6 Average is : 2 Handling Arguments in Java Application…
  • 12. UCSC 2003. All rights reserved.No parts of this material ma 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
  • 13. UCSC 2003. All rights reserved.No parts of this material ma • 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………
  • 14. UCSC 2003. All rights reserved.No parts of this material ma • 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………
  • 15. UCSC 2003. All rights reserved.No parts of this material ma • 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………
  • 16. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 17. UCSC 2003. All rights reserved.No parts of this material ma Using a Stream……….. • The close() is called on an output stream when you have no more information to send.
  • 18. UCSC 2003. All rights reserved.No parts of this material ma 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()
  • 19. UCSC 2003. All rights reserved.No parts of this material ma • A filter can associate with another filter. Filtering a Stream………..
  • 20. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 21. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 22. UCSC 2003. All rights reserved.No parts of this material ma 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 & FileOutputStream Byte streams stored in files on disk, CD-ROM or other storage devices. – DataInputStream & DataOutputStream A filtered byte stream from which data such as integers & Floating-point numbers can be read.
  • 23. UCSC 2003. All rights reserved.No parts of this material ma • 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……….
  • 24. UCSC 2003. All rights reserved.No parts of this material ma • 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……….
  • 25. UCSC 2003. All rights reserved.No parts of this material ma • To read more than one byte of data from the stream, call its read(byte[], int, int) method. Byte stream……….
  • 26. UCSC 2003. All rights reserved.No parts of this material ma • 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……….
  • 27. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 28. UCSC 2003. All rights reserved.No parts of this material ma • A data output stream requires the DataOutputStream(OutputStream) constructor which indicates the associated output stream. Data Streams………
  • 29. UCSC 2003. All rights reserved.No parts of this material ma 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().
  • 30. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 31. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 32. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 33. UCSC 2003. All rights reserved.No parts of this material ma 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 IOException This method writes the byte specified by the byteval to the file.
  • 34. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 35. UCSC 2003. All rights reserved.No parts of this material ma Error Handling Contd... java .lang.Object java .lang.Throwable java .lang.Exception IOException RuntimeException Java Exception class hierarchy
  • 36. UCSC 2003. All rights reserved.No parts of this material ma 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
  • 37. UCSC 2003. All rights reserved.No parts of this material ma 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
  • 38. UCSC 2003. All rights reserved.No parts of this material ma 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 protected using try Block Exception is caught and handled using catch block
  • 39. UCSC 2003. All rights reserved.No parts of this material ma 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
  • 40. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 41. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 42. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 43. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 44. UCSC 2003. All rights reserved.No parts of this material ma 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,Exception {
  • 45. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 46. UCSC 2003. All rights reserved.No parts of this material ma 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.
  • 47. UCSC 2003. All rights reserved.No parts of this material ma 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
  • 48. UCSC 2003. All rights reserved.No parts of this material ma 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 Throwing