0% found this document useful (0 votes)
2 views13 pages

Java IVunit

Adding more details helps others find the information they need in your upload. Boost your views by writing a clear, detailed title and description.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Java IVunit

Adding more details helps others find the information they need in your upload. Boost your views by writing a clear, detailed title and description.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

PROGRAMMING IN JAVA
Unit-4: Managing Errors and Exceptions-Syntax of Exception Handling Code-Using Finally
Statement-Throwing Our Own Exceptions-Applet Programming-Applet Life Cycle-Graphics
Programming-Managing Input/Output Files: Concept of Streams-Stream Classes-Byte Stream
Classes-Character Stream Classes – Using Streams-Using the File Class-Creation of Files-Random
Access Files-Other Stream Classes.

Exception Handling

 An exception is an abnormal event that arises during the execution of the program and disrupts the
normal flow of the program.
 Abnormality do occur when your program is running. For example, you might expect the user to
enter an integer, but receive a text string; or an unexpected I/O error pops up at runtime.
 Java has a built-in mechanism for handling runtime errors, referred to as exception handling. This is
to ensure that you can write robust programs for mission-critical applications.
 Exception handling is basically use five keyword as follows:

o try
o catch
o throw
o throws
o finally

Exception Handling
In java, when any kind of abnormal conditions occurs with in a method then the exceptions are
thrown in form of Exception Object i.e. the normal program control flow is stopped and an exception
object is created to handle that exceptional condition.
The method creates an object and hands it over to the runtime system. Basically, all the information
about the error or any unusual condition is stored in this type of object in the form of a stack. This object
created is called an exception object the process is termed as throwing an exception.
The mechanism of handling an exception is called catching an exception or handling an Exception or
simply Exception handling.
Advantages of Exception-handling in Java:
 Exception provides the means to separate the details of what to do when something out of the
ordinary happens from the main logic of a program.
 One of the significance of this mechanism is that it throws an exception whenever a calling method
encounters an error providing that the calling method takes care of that error.
 With the help of this mechanism the working code and the error-handling code can be
disintegrated. It also gives us the scope of organizing and differentiating between different error
types using a separate block of codes. This is done with the help of try-catch blocks.
 Furthermore the errors can be propagated up the method call stack i.e. problems occurring at the
lower level in the chain can be handled by the methods higher up the call chain .
Multiple catch blocks
Several types of exceptions may arise when executing the program. They can be handled by using
multiple catch blocks for the same try block. In such cases when an exception occur the run time system
will try to find match for the exception object from the parameters of the catch blocks in the order of
appearance. When a match is found corresponding catch block will be executed.
1
2

Steps in Handling Exception (try..catch)


The following are the tasks in handling exceptions
 Find the problem (Hit the exception)
 Inform that an error has occurred (Throw the exception)
 Receive the error (Catch the exception)
 Take corrective action (Handle the exception)
Finding the problem refers to identify the part of the program where the error may occur. That part of
the progrm has to be enclosed in try block and the catch block contais the codes thst represent the action
tobe taken when the error occurs.
Try_catch block
In Java exception handling is done with the help of try..catch block . The programmers can use the try..
catch block to handle the exceptions that suit their programs. This avoids abnormal termination of the
program.
Syntax
…..
…..
try
{
//Statements that may generate the exception
}
catch(exceptionclass object)
{
//Statements to process the exception
}
catch(exceptionclass object)
{
//Statements to process the exception
}
….
finally
{
//Statements to be executed before exiting exception handler
}
……
Try Block: Inside the try block we can include the statements that may cause an exception and throw an
exception.
Catch Bock: The catch block contains the code that handles the exceptions and may correct the
exceptions that ensure normal execution of the program. Catching the thrown exception object from the
try block by the corresponding catch block is called throwing an exception. The catch block should
immediately follow the try block.
We can have multiple catch block for a single try block.
Finally BLock: The finally block is always executed, regardless of whether or not an exception happens
during the try block, or whether an exception could be handled within the catch blocks. Since it always
gets executed, it is recommended that you do some cleanup here. Implementing the finally block is
optional.
Execution of try..catch blocks:

2
3

If no exception occurs during the running of the try-block, all the catch-blocks are skipped, and
finally-block will be executed after the try-block.
If one of the statements in the try-block throws an exception, the Java runtime ignores the rest of the
statements in the try-block, and begins searching for a matching exception handler. It matches the
exception type with each of the catch-blocks sequentially. If a catch-block catches that exception class or
catches a superclass of that exception, the statement in that catch-block will be executed. The statements
in the finally-block are then executed after that catch-block. The program continues into the next
statement after the try-catch-finally, unless it is pre-maturely terminated or branch-out.
If none of the catch-blocks matches, the exception will be passed up the call stack - if the method's
signature declares that this checked exception to be thrown; or the exception is an unchecked exception.
The current method terminates
Types of Exception Classes
 The base class for all Exception objects is [Link], together with its two subclasses
[Link] and [Link].
 The Error class describes internal system errors (e.g., VirtualMachineError, LinkageError) that
rarely occur. If such an error occurs, there is little that you can do and the program will be
terminated by the Java runtime.
 The Exception class describes the error caused by your program (e.g. FileNotFoundException,
IOException). These errors could be caught and handled by your program (e.g., perform an
alternate action or do a graceful exit by closing all the files, network and database connections).
There are three types of Exceptions:
1. Checked Exceptions
2. Unchecked Exceptions
3. Error
Checked Exceptions:
These are the exceptions which occur during the compile time of the program. The compiler checks
at the compile time that whether the program contains handlers for checked exceptions or not. These
exceptionsm must be handled to avoid a compile-time error by the programmer. These exceptions extend
the [Link] class These exceptional conditions should be predicted and recovered by an
application. Furthermore Checked exceptions are required to be caught.
For example if you call the readLine() method on a BufferedReader object then the IOException may
occur or if you want to build a program that reads data using the method readLine() then the method
should have clode to handle the IOException.
Here is the list of checked exceptions.
 NoSuchFieldException
 InstantiationException
 IllegalAccessException
 ClassNotFoundException
 NoSuchMethodException
 CloneNotSupportedException
 InterruptedException
Unchecked Exceptions:
Unchecked exceptions are the exceptions which occur during the runtime of the program. Unchecked
exceptions are internal to the application and extend the [Link] that is inherited
from [Link] class. These exceptions cannot be predicted and recovered like programming
bugs, such as logic errors or improper use of an API. These type of exceptions are also called Runtime
exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc.
3
4

The most common unchecked exception is the ArithmeticException which occurs when something
tries to divide by zero.
Here is the list of unchecked exceptions.
 IndexOutOfBoundsException
 ArrayIndexOutOfBoundsException
 ClassCastException
 ArithmeticException
 NullPointerException
 IllegalStateException
 SecurityException
Error :
The errors in java are external to the application.
These are the exceptional conditions that could not be
usually predicted by the application and also could
not be recovered from. Error exceptions belong to
Error and its subclasses are not subject to the catch
or Specify requirement. An Error indicates serious
problems that a reasonable application should not try
to catch. Most such errors are abnormal conditions.
Example for error are serious and unrecoverable
exceptions like running out of memory, stack
overflow etc
Here is the list of unchecked exceptions
 IllegalAccessErrors
 NoSuchFieldError
 InternalError
 StackOverFlowError
Finally clause
 The code in the finally block will be executed even or not the exception arise inside the block of
code.
 The finally block is normally used for clean up activities like file closing, flushing buffers etc.
 The finally block is optional.
Example:
/* Finally block*/
class finallydemo
{
public static void main(String args[])
{
int a,b,c;
a=[Link](args[0]);
b=[Link](args[1]);

try
{
c=a/b;
[Link](a+" / "+b+"="+c);
}
4
5

catch(ArithmeticException e)
{
[Link]("Division by zero error occurred");
[Link](e);
}

finally
{
[Link]("Inside finally block");
}
}
}

throws Keyword
If a method is capable of causing an exception that it does not handle, it must specify this behaviour
so that callers of the method can guard themselves against that exception. When throws clause is used
try..catch block is not needed.
type method-name(paramlist) throws exception-list
{
//…..
}
throws clause lists the types of exceptions that a method might throw. It is necessary for all
exceptions, except those of type Error or RuntimeException, or any of their subclasses.
Example:
/* throws clause example */
import [Link].*;
class readip
{
public static void main(String args[]) throws IOException
{
int a;
String name;
DataInputStream din=new DataInputStream([Link]);
[Link]("Enter the name:");
name=[Link]();
[Link]("Enter the register number:");
a=[Link]([Link]());
[Link]("\nNAME:"+name);
[Link]("[Link]:"+a);
}
}

Creating and Executing an Applet

5
6

An applet is a Java program that runs under a Java-compatible browser such as Netscape or HotJava.
This feature allows users to display graphics and to run programs over the Internet via the WWW
relatively easily. An applet allows web documents to be both animated and interactive!

Creating and Executing applet

Step 1: Import applet package and awt package


To create an applet, you must import the Applet class. This class is in the [Link] package
The Applet class contains code that works with a browser to create a display window.
We also need to import the [Link] package. The "awt” stands for “Abstract Window Toolkit”. The
[Link] package includes classes for:

 Drawing lines and shapes


 Drawing letters
 Setting colors
 Choosing fonts etc.

Step 2: Extend the Applet class


Then, a class must be defined that inherits from the class [Link]. The Applet class is the
standard class inherited for writing applets. It contains the methods to paint to the screen and the
window. The inherited class must be declared public
Step 3: Override the paint method if you want to draw
The paint method needs the Graphics object as its parameter.
public void paint(Graphics g) { … }
public says that anyone can use this method. void says that it does not return a result. A Graphics
(short for “Graphics context”) is an object that holds information about a painting. It remembers what
color you are using. It remembers what font you are using
Syntax:

1. import [Link].*;
2. import [Link].*;
3. public class MyApplet extends Applet
4. {
5. public void paint(Graphics g)
6. {
7. //Statements
8. }
9. }

where Myapplet is the name of the class.


Save the class with .java extension.
Step 4: Compiling the Program
Once you have saved your program, you need to compile it using the Java compiler. At your command
line, enter the command "javac [Link]". This command will compile your code so that you now
have a [Link] file. If you receive any error messages, look back at the above code and make the
necessary corrections.
6
7

Step 5: Creating the HTML document


To run the applet we need to create the HTML document. The BODY section of the HTML document
has a tag called APPLET that you can use to run the applet.
The HTML looks something like this:

<HTML>
<BODY>

<APPLET CODE= "class file name"


WIDTH=width in pixels
HEIGHT=height in pixels>
</APPLET>

</BODY>
</HTML>
Save the file with .html extension.
Step 6:Running an applet
The applet can be run in two ways
1. By using appletviewer
To run the appletviewer utility type appletviewer [Link]
2. By running in web browser.
In the web browser bar give the full address of your html file.

Graphics Class

The Graphics class is the class used to allow a component to draw onto itself. The Graphics class is
located in the [Link] package. To use the Graphics class, you have to pass a Graphics object as argument
to paint() method.
The Graphics class provides the framework for all graphics operations within the AWT. It plays two
different, but related, roles. First, it is the graphics context. The graphics context is information that will
affect drawing operations. This includes the background and foreground colors, the font, and the location
and dimensions of the clipping rectangle (the region of a component in which graphics can be drawn).
Second, the Graphics class provides methods for drawing simple geometric shapes, text, and images to
the graphics destination. All output to the graphics destination occurs via an invocation of one of these
methods.
Coordinate System
Note that the basic AWT coordinate system for the Graphics context methods goes as follows:
* Origin (0,0) - top left hand corner
* x (in pixels) - increases towards the right
* Maximum x = width - 1
* y (in pixels) - increases towards the bottom
* Maximum y = height -1
We can obtain the dimensions of a component in two ways. The getSize() method returns an
instance of the Dimension class, which provides direct access to its height and width variables. The
component class includes the methods getHeight() and getWidth() so you can obtain each of these
dimensions separately.
Negative values and positive values beyond the width and height of the drawing area do not cause errors
7
8

but are treated as valid coordinates (though, any drawing in those areas will be unseen, of course.)

Basic Graphics Commands

1) setColor(Color c)

Set the current pen color, where c has several standard choices such as [Link], [Link],
[Link], etc.

2) drawLine(int x1, int y1, int x2, int y2)

Draw a line between points (x1,y1) and (x2,y2)

3) drawRect (int x, int y, int width, int height)


Draws a rectangle, (x,y) are the coordinates of the top left corner, the bottom right corner will be
at (x+width,y+height)
4) fillRect (int x, int y, int width, int height)

Draws (fills) a rectangle, (x,y) are the coordinates of the top left corner, the bottom right corner will
be at (x+width,y+height).

5) drawOval (int x, int y, int width, int height)


Draws an oval bounded by the rectangle specified by these parameters.
6) fillOval (intx, int y, int width, int height)

Draws (fills) an oval bounded by the rectangle specified by these parameters.

7)draw3DRect (int x, int y, int width, int height, int arcWidth, boolean raised)

Draws a rectangle with shaded sides that provide a 3-D appearance.

8) fill3DRect (int x, int y, int width, int height, boolean raised)

Draws (fills) a rectangle with shaded sides that provide a 3-D appearance.

9) drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight)
10) fill3DRect (int x, int y, int width, int height, int arcWidth, int arcHeight)

Draws (fills) a rectangle with rounded corners.

11) drawArc(int x,int y,int width, int height, int startAngle, int arcAngle)

An arc is formed by drawing an oval between a start angle and a finish angle. The start angle is
measured from the positive x-axis and is expressed in degrees. The arc angle is expressed in
degrees from the start angle. Angles extend from the center of the bounds box.
8
9

12) drawPolyline (int[] x, int[] y, int N)

Draws lines connecting the N points given by the x and y arrays.

13) drawPolygon (int[] x, int[] y, int N)

Draws lines connecting the points given by the x and y arrays. Connects the last point to the first if
they are not already the same point.

The following figure shows some of the drawing primitives

I/O Streams
The Java platform includes a number of packages that are concerned with the movement of data into
and out of programs. These packages differ in the kinds of abstractions they provide for dealing with I/O
(input/output).
The [Link] package defines I/O in terms of streams. Streams are ordered sequences of data that
have a source (input streams) or destination (output streams). The I/O classes isolate programmers from
the specific details of the underlying operating system, while enabling access to system resources
through files and other means.

A program uses an input stream to read data from a source, one item at a time:

9
10

A program uses an output stream to write data to a destination, one item at time:

Streams are byte-oriented or character-oriented. Each type has input streams and output streams.

Byte-oriented streams: Used for general-purpose input and output. Data may be primitive data types or
raw bytes.
Character-oriented streams.:Specialized for character data. Transforms data from/to 16 bit Java char
used inside programs to UTF format used externally.

Byte Stream
Byte streams can be used to read or write bytes serially from an external device. All the byte streams
are derived from the abstract superclass InputStream and OutputStream,.

10
11

Character-stream class Description


Reader Abstract class for character-input streams
BufferedReader Buffers input, parses lines
LineNumberReader Keeps track of line numbers
CharArrayReader Reads from a character array
InputStreamReader Translates a byte stream into a character stream
FileReader Translates bytes from a file into a character stream
FilterReader Abstract class for filtered character input
PushbackReader Allows characters to be pushed back
PipedReader Reads from a PipedWriter
StringReader Reads from a String
Writer Abstract class for character-output streams
BufferedWriter Buffers output, uses platform's line separator
CharArrayWriter Writes to a character array
FilterWriter Abstract class for filtered character output
OutputStreamWriter Translates a character stream into a byte stream
FileWriter Translates a character stream into a byte file
PrintWriter Prints values and objects to a Writer
PipedWriter Writes to a PipedReader
StringWriter Writes to a String

InputStream Class
[Link] is an abstract class that contains the basic methods for reading raw bytes of data
from a stream. Although InputStream is an abstract class, many methods in the class library are only
specified to return an InputStream
Character Streams
Character Stream:
Character streams are like byte streams, but they contain 16-bit Unicode characters rather than
eight-bit bytes.
They are implemented by the Reader and Writer classes and their subclasses.
11
12

Readers and Writers support essentially the same operations as InputStreams and OutputStreams,
except that where byte-stream methods
operate on bytes or byte arrays, character-stream methods operate on characters, character arrays, or
strings.

Why use character streams?


 The primary advantage of character streams is that they make it easy to write programs that
are not dependent upon a specific character encoding, and are therefore easy to internationalize.
 A second advantage of character streams is that theyare potentially much more efficient than
byte [Link] implementations of many of Java's original bytestreams are oriented around
byte-at-a-time read and write operations. The character-stream classes, in contrast,are oriented
around buffer-at-a-time read and writeoperations.

Files
The File class deals with the machine dependent files in a machine-independent manner i.e. it is
easier to write platform-independent code that examines and manipulates files using the File class. This
class is available in the [Link] package.
The [Link] is the central class that works with files and directories. The instance of this class
represents the name of a file or directory on the host file system.
When a File object is created, the system doesn't check to the existence of a corresponding
file/directory. If the file exist, a program can examine its attributes and perform various operations on
the file, such as renaming it, deleting it, reading from or writing to it.
It also maintains two system-dependent properties, for you to write programs that are portable:
1. Directory Separator: Windows systems use backslash '\' (e.g., "c:\jdk\bin\[Link]"), while
Unixes use forward slash '/' (e.g., "/usr/jdk/bin/[Link]"). This system-dependent property is
maintained in the static field [Link] (as String) or [Link]. (They failed to follow
the naming convention for constants, which was adopted in JDK 1.2.)
2. Path Separator: Windows use semi-colon ';' to separate paths (or directories) white Unixes use
colon ':'. This system-dependent value can be retrieved from static field [Link] (as
String) or [Link].
Constructors:
 File(path)
Create File object for default directory (usually where program is located).
 File(dirpath,fname)
Create File object for directory path given as string.
 File(dir, fname)
Create File object for directory.
Methods that are used with the file object to get the attribute of a corresponding file
 [Link]()
Returns true if file exists.
 [Link]()
Returns true if this is a normal file.
 [Link]()
Returns true if "f" is a directory.
 [Link]()
Returns name of the file or directory.
12
13

 [Link]()
Returns true if file is hidden.
 [Link]()
Returns time of last modification.
 [Link]()
Returns number of bytes in file.
 [Link]()
Returns path name.
 [Link]()
Deletes the file.
 [Link](f2)
Renames f to File f2. Returns true if successful.
 [Link]()
Creates a file and may throw IOException.
 [Link]()
Makes the file read only.

13

You might also like