JAVA-UNIT-4-Managing Exception, Applet Programming PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

UNIT-4

Managing Exceptions, Applet Programming


Introduction
In this unit we will learn:
• How exception and error handling works.
• To use try, throw and catch to detect,
indicate and handle exceptions, respectively.
• To use the finally block to release resources.
• How stack unwinding enables exceptions not
caught in one scope to be caught in another
scope.
• How stack traces help in debugging.
• How exceptions are arranged in an exception
class hierarchy.
• To declare new exception classes.
• To create chained exceptions that maintain
complete stack trace information.
• Exception – an indication of a problem that
a
occurs during a program’s execution
• Exception handling – resolving exceptions that
may occur so program can continue or
terminate gracefully
• Exception handling enables programmers to
create programs that are more robust and
fault-tolerant
• Exception handling helps improve a program’s
fault tolerance
Examples

– ArrayIndexOutOfBoundsException – an
attempt is made to access an element past the
end of an array
– ClassCastException – an attempt is made
to cast an object that does not have an is-a
relationship with the type specified in the cast
operator
– NullPointerException – when a null
reference is used where an object is expected
Types of Errors
• Errors may broadly be classified into two
categories
1)Compile-time error
2)Run-time error
Compile-Time Error
• All syntax errors will be detected and
displayed by the Java compiler and therefore
these errors are known as compile-time errors
• Whenever compiler display an error ,it will not
create the .class file .It is therefore necessary
that we fix all the errors before we can
successfully compile and run the program
/*This program contains an error*/
class error
{
public static void main(string args[])
System.out.println(“Hello Java”) //missing ;
}
Examples
• Missing semicolons
• Missing brackets
• Use of undeclared variables
Run-Time Errors
• Sometimes a program may compile
successfully creating .class file but may not
run properly.
• Such program may produce wrong results due
to wrong logic or may S terminate due to
errors such as stack overflow
• Examples
• Dividing an integer by zero
• Accessing an element that is out of the
bounds of an array
class error
{
public static void main(string args[])
int a=10;
int b=5;
int c=5;
int x=a/b-c; //division by zero
System.out.println(“x=“ + x);
}
Exceptions
• An exception is a condition that is caused by a
run-time error in the program
• When the Java interpreter encounters an error
such as dividing an integer by zero, it creates
an exception object and throws it
• If an exception object is not caught and
handled properly ,the interpreter will display
an error message and will terminate the
program
• If we want program to continue with the
execution of the remaining code , then we should
try to catch the exception object thrown by the
error condition and then display appropriate
message for taking corrective action . This task is
known as exception handling .
• The mechanism suggests incororation of a
separate error handling code that performs
following tasks
1.Find the problem(Hit the exception)
2.Inform that the error has occurred(Throw the
exception)
3.Receive the error information(catch the
exception)
4.Take corrective actions(Handle the exception)
Common JAVA Exceptions
1.ArithematicException-Caused when there’s
not enough memory to allocate a new object
2.OutOfMemoryException-Caused when there’s
not enough memory to allocate a new object
3.IOException-Caused by general I/O
failure,such as inability to read a file
Syntax of Exception handling Code
• The basic concepts of exception handling is
throwing an exception and catching it,as
illustrated in figure below
Exception handling Mechanism
• Java uses a keyword try to preface a block of
code that is likely to cause an error condition
and throw an exception
• A catch block defined by the keyword catch
“catches” the exception thrown by the try
block and handles it appropriately
• The catch block is added immediately after
the try block
• The following example illustrates the use of
simple try and catch statements
………………..
………………..
try
{
statement; //generates an exception
}
catch(Exception-type e)
{
statement; //processes the exception
}
………………………..
…………………………….
• The try block can have one or more
statements that could generate an exception
• If any one statement generates an exception
the remaining statements in the block are
skipped and execution jumps to the catch
block that is placed next to the try block
Multiple Catch Statements
• It is possible to have more than one catch
statement in the catch block as illustrated below
................
.................
try
{
statement;
}
catch( Exception-Type-1 e)
{
statement;
}
catch( Exception-Type-2 e)
{
statement;
}
.
.
.
catch( Exception-Type-N e)
{
statement;
}
Using Finally Statement
• Java supports another statement known as
finally statement that can be used to handle
an exception that is not caught by any of the
previous catch statements
• Finally block can be used to handle any
exception generated within a try block
• It may be added immediately after the try
block or after the last catch block shown as
below
try try
{ {
……. …………..
……. }
} catch
finally {
{ ……………….
……… }
…….. catch
} {
……………….
}
.
.
.
finally
{
……………………..
}
• When a finally block is defined this is
guaranteed to execute, regardless of whether
or not an exception is thrown
• As a result, we can use it to perform certain
operations such as closing files and releasing
system resources
Throwing Our Own Exceptions
• There may be times when we would like to
throw our own exception
• This is done by using the keyword throw as
follows
throw new Throwable-subclass;
• Example
throw new ArithemeticException();
throw new NumberFormatException();
Program to demonstrate(p239-240)
Using Exceptions for Debugging
• Exception –handling mechanism can be used
to hide errors from rest of the program
• It is possible that the programmers may
misuse this technique for hiding errors rather
than debugging the code
• Exception –handling mechanism may be
effectively used to locate the type and
Applet Programming
Introduction
• Applets are small Java programs that are
primarily used in Internet computing.
• They can be transported over the Internet
from one computer to another and run using
Applet viewer or any web browser that
supports Java
• Applet like any application program can
perform arithmetic operations, display
graphics, play sounds, accept user input,
create animation and play interactive games
Local and Remote Applets
• An applet developed locally and stored in a local
system is known as a local applet. When a web
page is trying to find local applet, it does not
need to use Internet and therefore the local
system does not require internet connection
• A remote applet is that which is developed by
someone else and stored on a remote computer
connected to the internet. If our system is
connected to Internet, we can download the
remote applet onto our system via at the Internet
and run it
Loading local and Remote Applets
How Applets Differ from Applications
• Although both applets and stand-alone
applications are Java programs,there are
significant difference between them
• Applets are not fully-featured application
programs. They are usually written to
accomplish a small task or a component of a
task
• Since they are designed for use on Internet,
they impose certain limitations and
restrictions in their design
• Applets do not use the main() method for initiating the
execution of the code. Applets, when loaded
automatically call certain methods of Applet class to
start execute the applet code
• Unlike stand-alone applications applets cannot be run
independently. They are run from inside a web page
using a special feature known as HTML tag
• Applets cannot read from or write to the files in the
local computer
• Applets cannot communicate with other servers on the
Internet
• Applets cannot run any program from the local
computer
• Applets are restricted from using libraries from other
languages such as c or c++
All these restrictions and limitations are placed in the
interest of security of systems
Preparing to Write Applets
• To create applets , one will need to know
1.When to use applets
2.How an applet works
3.What sort of features an applet has
4.Where to start when we first create our own
applets
• Before one tries to write applets,one must make
sure that Java is installed properly and also
ensure that either the Java appletviewer or a
Java-enabled browser is available
• The steps involved in developing and testing
an applet are
1.Building an applet code(.java file)
2.Creating an executable applet(.class file)
3.Designing a web page using HTML tags
4.Preparing<APPLET> tag
5.Incorporating <APPLET> tag into web page
6.Creating HTML file
7.Testing the applet code
Building Applet Code
• Applet code uses the services of two classes, namely,
Applet and Graphics from Java class library
• The Applet class which is contained in the java.applet
package provide life and behavior
to the applet through its methods such as init(),start()
and point()
• Unlike the applications, where Java calls the main()
method directly to initiate the execution of the
program, when an applet is loaded, Java automatically
calls a series of Applet class methods for starting,
running and stopping the applet code
• The Applet class therefore maintains the life cycle of an
applet
• The paint() method of the Applet class, when it is
called, actually displays the result of the applet
code on the screen
• The output may be text, graphics or sound
• The paint() method, which requires a Graphics
object as an argument, is defined as follows
public void paint(Graphics g)
• This requires that the applet code imports the
java.awt package that contains Graphics class
• All output operations of an applet are performed
using the methods defined in the Graphics class
An applet code will have general format as

import java.awt.*;
import java.applet.*;
…………………………….
……………………………
public class appletclassname extends Applet
{
………………………………..
………………………………..
public void paint(Graphics g)
{
……………………………….
……………………………….
}
………………………………..
……………………………….
}
• The appletclassname is the main class for the
applet
• when the applet is loaded,Java creates an
instance of this class and then a series of
Applet class methods are called on that
instance to execute the code
The HelloJava Applet
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
{
public void paint (Graphics g)
{
g.drawString(“Hello Java”, 10, 100);
}
}
Applet Life Cycle
• Every Java applet inherits a set of default
behaviours from the Applet class
• As a result, when applet is loaded, it undergoes a
series of changes in its state as shown in figure
below
• The applet states include:
1. Born on initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
• Initialization stateApplet enters the initialization
state when it is first loaded.This is achieved by calling
the init() method of Applet class.The applet is born.At
this stage,we may create objects needed by the
applet,set up initial values,load images or fonts,set up
colors.
The initialization occurs only once in the applet’s life
cycle. To provide any of the behaviour mentioned
above, we must override the init() method:
public void init( )
{
...................
.....................(Action)
}
• Running StateApplet enter running state when the system calls the
start() method of Applet class3.This occurs automatically after the applet
is initialized.Unlike init() method,the start() method may be called more
than once.
public void start()
{
...................
................... (Action)
}
• Idle or Stopped StateAn applet becomes idle when it is stopped from
running. Stopping occurs automatically when we leave the page
containing the currently running applet.We can also do so by calling the
stop() method explicitly
public void stop()
{
...................
................... (Action)
}
• Dead stateAn applet is said to be dead when it is removed from
memory.This occurs automatically by invoking the destroy() method
when we quit the browser. Destroying stage occur only once in the
applet’s life cycle
public void destroy ()
{
...................
................... (Action)
}
• Display State Applet moves to the display state whenever it has
to perform some output operations on the screenThis happens
immediately after the applet enters into the running state.The
paint() method is called to accomplish this task
public void paint(Graphics g)
{
...................
................... (Action)
Creating an Executable Applet
• Executable applet is nothing but the .class file
of the applet, which is obtained by compiling
the source code of the applet
• Compiling an applet is exactly the same as
compiling an application. Therefore we can
use Java compiler to compile the applet
• Consider the HelloJava applet that has been
stored in a file called HelloJava.java
• Following are the steps required for compiling
HelloJava applet
1. Move to the directory containing the source
code and type the following command
javac HelloJava.java
2. The compiled output file called
HelloJava. Class is placed in the same
directory as the source
3. If any error message is received then we must
check for errors, correct them and compile
applet again
Designing a Web Page
• Java applets are programs that reside on web pages.In
order to run a Java applet, it is first necessary to have a
web page that references that applet
• A web page is basically made up of text and HTML tags
that can be interpreted by a web browser or an applet
viewer
• Like Java source code ,it can be prepared using any
ASCII text editor
• Web pages are stored using a file extension .html
• HTML files should be stored in same directory as the
compiled code of applets
• Web pages include both text that we want to display
and HTML tags to web browsers
• A web page is marked by an opening HTML
tag <HTML> and a closing HTML tag </HTML>
and is divided into following 3 major sections
1. Comment section(optional)
2. Head section(optional)
3. Body section
Applet Tag
• We include a pair of <APPLET> and
</APPLETS> tags in the body section
• The <APPLET……> tag supplies the name of the
applet to be loaded and tells the browser how
much space the applet requires. The ellipses
in the tag <APPLET…..> indicates that it
contains certain attributes that must be
specified
• <APPLET> tag given below specifies minimum
requirements to place HelloJava applet on
web page
<APPLET>
CODE=HelloJava.class
WIDTH=400
HEIGHT=200>
</APPLET>
• This HTML code tells the browser to load the
compiled Java applet HelloJava.class,which is
in the same directory as the HTML file
• It also specifies display area for applet output
400 pixels width and 200 pixels height
Adding Applet to HTML File
• We can put together the various components
of the web page and create a file known as
HTML file.Insert the <APPLT> tag in the page
at the place where the output of the applet
must appear
• Following is the content of the HTML file that
is embedded with the <APPLET> tag
<HTML>
<!This page includes a welcome title>
<HEAD>
<TITLE>
Welcome to Java Applets
</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> Welcome to the world of Applets </H1>
</CENTER>
<BR>
<CENTER>
<APPLET
CODE=HelloJava.class
WIDTH=400
HEIGHT=200 >
</APPLET>
</CENTER>
</BODY>
</HTML>
Running the Applet
• After creating applet files as well as HTML file
containing the applet, we must have the
following files in our current directory
HelloJava.java
HelloJava.class
HelloJava.html
• To run an applet, we require one of the following
tools:
1.Java-enabled web browser( HotJava or
Netscape)
2.Java appletviewer
• The appletviewer is available as a part of the
Java Development kit
• We can use it to run applet as follows:
appletviewer HelloJava.html
More about Applet Tag
• We have used <APPLET > tag in its simplest
form,where it creates a space of the required
size and then displays the applet output in
that space
• The syntax of the <APPLET> tag is a little more
complex and includes several attributes that
can help us better integrate our applet into
the overall design of the web page
• The syntax of the <APPLET> tag in full form is
<APPLET
[ CODEBASE =codebase_URL ]
CODE = AppletFileName.class
[ ALT = alternate_text }
[ NAME = applet_instance_name ]
WIDTH = pixels
HEIGHT= pixels
[ ALIGN = alignment ]
[ VSPACE = pixels ]
[ HSPACE = pixels ]
>
[ < PARAM NAME = name1 VALUE = value1> ]
[ < PARAM NAME = name2 VALUE = value2> ]
................................
.................................
[Text to be displayed in the absence of Java ]
</APPLET>
Attributes of APPLET Tag
CODE=AppletFileName.classSpecifies the
names of the applet class to be loaded.That is
the name of the already compiled .class file
WIDTH=pixelsThese attribites specify the
HEIGHT=pixels width and height of the space
on the HTML page that will be reserved for
the applet
HSPACE=pixels(optional)Used only when
ALIGN is set to LEFT or RIGHT
Passing Parameters to Applets
• We can supply user-defined parameters to an
applet using <PARAM…>tags.Each <PARAM….>
tag has a name attribute such as color and a
value attribute such as red
• Inside the applet code, the applet can refer to
that parameter by name to find its value
• For eg,we can change colour of the text displayed
to red by an applet as follows
<APPLET>
<PARAM=color VALUE=“red”>
</APPLET>
• Similarly ,we can change the text to be displayed
by an applet by supplying new text to the applet
through <PARAM…> tag as follows
<PARAM NAME=text VALUE=“I love Java”>
• To set up and handle parameters, we need to do
two things
1.Include appropriate <PARAM..> tags in the HTML
document
2.Provide code in the applet to parse these
parameters
• Parameters are passed on an applet when it is
loaded.We can define init() method in the applet
to get hold of the parameters defined in the
<PARAM…> tags.This is done using the
getParameter() method,which takes one string
argument representing the name of the
parameter and returns a string containing value
of that parameter
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html

<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Aligning the Display
• We can align the output of the applet using
the ALIGN attribute
• This attribute has one of the nine values
LEFT,RIGHT,TOP,TEXT TOP, MIDDLE
,ABSMIDDLE,BASELINE,BOTTOM,ABSBOTTOM
• Eg: ALIGN=LEFT will display the output at the
left margin of the page
HTML file with ALIGN Attribute
<HTML>
<HEAD>
<TITLE> Here is an applet </TITLE>
</HEAD>
<BODY>
<APPLET CODE=HelloJava.class
WIDTH=400
HEIGHT=200
ALIGN=RIGHT
</APPLET>
</BODY>
</HTML>
More About HTML Tags
• HTML supports a large number of tags that
can be used to control the style and format of
the display of web pages
• Below are some important HTML tags and
their functions
• <HTML>……</HTML> --- Signifies the
beginning and end of HTML file
• <HEAD>……</HEAD> ---- This tag may
include details about the web page. Usually
contains <TITLE> tag within it
• <TITLE>…..</TITLE> --- The text contained in it will
appear in the title bar of the browser
• <BODY>…..</BODY> ----This tag contains the
main text of the web page. It is the place
where the <APPLET> tag is declared
• <H1>……..</H1> -----Header tags
Displaying Numerical Values
• In applets, we can display numerical values by
first converting them into strings and then
using the drawString() method of Graphics
class
• We can do this easily by calling the ValueOf()
method of string class
• Following program illustrates how an applet
handles numerical values
import java.awt.*;
import java.applet.*;
public class (NumValues extends Applet
{
public void paint(Graphics g)
{
int value1=10;
int value2=20;
int sum=value1+value2;
String s=“sum:”+String.valueOf(sum);
g.drawString(s, 100, 100);
}
}
• The applet program above when run using
the following HTML file displays the output
<html>
<applet
code=NumValue.class
width=300
height=300>
</applet>
</html>
Getting Input from the User
• Applets work in a graphical
environment.Therefore ,applets treat inputs as
text strings.We must first create an area on
the screen in which user can type and edit
input items(any data type)
• This is done using the TextField class of the
applet package.Once text fields are created for
receiving input,we can type the values in the
fields and edit them,if necessary
• Next step is to retrieve the items from the
fields for display of calculations,if any
• The text fields contain items in string
form.They need to be converted to the right
form,before thay are used in any
computations
• The results are then converted back to strings
for display
Program demonstrating interactive input to an applet
import java.awt.*;
import java.applet.*;
public class UserIn extends Applet
{
TextField text1,text2;
text1=new TextField(8);
text2=new TextField(8);
add (text1);
add (text2);
text1.setText (“0”);
text2.setText (“0”);
}
public void paint(Graphics g)
{
int x=0,y=0,z=0;
String s1,s2,str;
g.drawString("Enter the number in each box",10,50);
try
{
s1=tex1.getText();
x=Integer.parseInt(s1);

s2=text2.getText();
y=Integer.parseInt(s2);
}
catch(Exception ex)
{
}
z=x+y;
s=String.valueOf (z);
g.drawString("Sum is",10,15);
g.drawString(s, 100, 75);
}
Public Boolean action (Event event , Object object)
{
repaint ( );
return true;
}
}
Run the applet UserIn using the following steps:
1. Type and save the program(.java file)
2. Compile the applet(.class file)
3. Write an HTML document(.html file)

<html>
<applet
code=UserIn.class
width=300
height=200>
</applet>
</html>
4. Use the applet viewer to display the results

You might also like