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

Docsity Programming in Java by Balagurusamy

The document provides an overview of exception handling in Java, detailing the types of errors (compile-time and run-time) and their common causes. It explains the concept of exceptions, how to handle them using keywords like try, catch, and finally, and illustrates with examples. Additionally, it touches on applets, their purpose, and the steps involved in creating and running them.

Uploaded by

arthy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views68 pages

Docsity Programming in Java by Balagurusamy

The document provides an overview of exception handling in Java, detailing the types of errors (compile-time and run-time) and their common causes. It explains the concept of exceptions, how to handle them using keywords like try, catch, and finally, and illustrates with examples. Additionally, it touches on applets, their purpose, and the steps involved in creating and running them.

Uploaded by

arthy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming in java by

balagurusamy
Java Programming
Bharathiar University
67 pag.

Document shared on [Link]


Unit IV
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Exception
Handling

Document shared on [Link]


Managing Errors and Exceptions

• Type of Errors

Type of Error

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])


Compile-Time Errors Run-Time Errors

All Syntax errors will be detected and Sometime a program may compile successfully
displayed by the Java Compiler and therefore but may produce the wrong results due to wrong
these errors are known as Compile-Time logic or terminate due to error is known as Run-
Errors. Time Errors.

Document shared on [Link]


Illustration of Compile-Time Errors
Class Error1
{
Public static void main(String args[])
{
[Link](“Hello Java”) //Missing;
}
} Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

[Link] :7: ‘;’ expected


[Link](“Hello Jaav”)
^
1 error

Document shared on [Link]


The Most Common Compile Time Errors are

• Missing Semicolons
• Missing (or mismatch of) brackets in classes and methods
• Misspelling of identifiers and keywords
• Missing double quotes in strings
• Use of undeclared variables
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• Incompatible types in assignments/initialization


• Bad references to objects
• Use of = in place of == operator
• And so on

Document shared on [Link]


Illustration of Run-Time Errors
Class Error2
{
Public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

int x=a/(b-c); //Division by Zero


[Link](“x=“+x);
int y=a/(b+c);
[Link](“y=“+y);
} [Link]: / by zero
at [Link]([Link])
}

Document shared on [Link]


The Most Common Compile Time Errors are
• Dividing an integer by zero
• Accessing an element that is not of the bounds of an array
• Trying to store a value into an array of an incompatible class or
type
• Trying to cast an instance of a class to one of its subclasses
• Passing a parameter that is not in a valid range or value for a
method Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• Trying to illegally changes the state of a thread


• Attempting to use a negative size for an array
• Using a null object reference as a legitimate object reference to
access a method or a variable
• Converting invalid string to a number
• Accessing a character that is out of bounds of a string

Document shared on [Link]


Exception

• An exception is an event, which occurs during the execution of


a program, that disrupts the normal flow of the program's
instructions.

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Exception = Exceptional Event

Document shared on [Link]


Exception Handling
• Java exception handling is a mechanism for handling exception by
detecting and responding to exceptions in a systematic, uniform
and reliable manner

Any exceptions not specifically handled within a


Java program are caught by the Java run time
environment
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• Exceptions
– A Method in Java throws exceptions to tell the calling code:
“Something bad happened. I failed.”

Exceptions are objects of Exception or Error class


or their subclasses.

Document shared on [Link]


Error Handling code that performs the
following tasks

• Find the problem ( Hit the exception )

• Inform that an error has occurred ( Throw the exception )

• Receive the error information ( Catch the exception )


Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• Task corrective actions ( Handle the exception )

Document shared on [Link]


Exception Classes

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Document shared on [Link]


System Errors
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several moreclasses
IllegalArgumentException
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

LinkageError Several moreclasses

System errors are thrown by JVM


and represented in the Error class. VirtualMachineError
The Error class describes internal
Error
system errors. Such errors rarely
occur. If one does, there is little AWTError
you can do beyond notifying the
user and trying to terminate the Several moreclasses
program gracefully.

Document shared on [Link]


Exceptions
Exception describes errors caused
by your program and external
circumstances. These errors can ClassNotFoundException
be caught and handled by your
program IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Document shared on [Link]


Runtime Exceptions

ClassNotFoundException

Runtime Exception
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Document shared on [Link]


Exception Handling Keywords

Keywords:
try catch
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

finally

throw throws
Document shared on [Link]
Syntax of Exception Handling Code

Try Block
Exception object creator
Statement that causes an exception

Throws exception object

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Catch Block
Exception Handler
Statement that handles the exception

Document shared on [Link]


Example
Class Error3
{
Public static void main(String args[])
{
Int a=10;
Int b=5;
Int c=5;
Int x,y;
try
Output
{
Division by Zero
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])
x=a/(b-c);
Y= 1
}
catch(ArithmeticException e)
{
[Link](“Division by Zero”);
}
Y=a/(b+c);
[Link](“y=“+y);
}
}

Document shared on [Link]


Multiple Catch Statement

Syntax

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Example
Class Error4
{
Public static void main(String args[])
{
Int a[]={5,10};
Try
{
Int x=a[2]/b-a[1];
Catch(ArithmeticException e)
{ Output1:
[Link](“Division by Zero”);
Array Index Error
}
Catch(ArrayindexOutOfBoundsException e)
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])
Y=2
{
[Link](“Array Index Error”);
}
Catch(ArrayStoreException e)
{
[Link](“Wrong data type”);
}
Int y=a[1]/a[0];
[Link](“y=“+y);
}
}

Document shared on [Link]


Using finally Statement
Syntax

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Finally Example

finally
{
Int y=a[1]/a[0];
[Link](“Y=“+y);
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Throwing Our Own Exception
• There may be times when we would like to throw our own
exceptions. We can do this by using the keyword throw as
follows:
throw new Throwable_subclass;
Example
throw new ArithmeticException();
throw new NumberFormatException();
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Throwing our own exception
Output:
Caught my exception
Number is two small
I am always here

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Applet
Programming
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


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 the Applet Viewer or any Web
Browser that supports Java
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• A web page can now contain not only a simple text or a static
image but also a java applet which, when run, can produce
graphics, sounds and moving images.

Document shared on [Link]


Local and Remote Applets

Local Applet

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Remote Applet

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


How applets differ from Applications

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Preparing To Write Applets

• Let us consider the situations when we might need to use


applets
– When we need something dynamic to be included in the display of a
Web Page.
– When we require some “flash” outputs.
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])
– When we want to create a program and make it available on the
Internet for us by others on their computers.

Document shared on [Link]


Cont.,
• The steps involved in developing and testing an applet are

– Building an applet code (.java file)


– Creating an executable applet (.class file)
– Designing a Web page using HTML tags
– Preparing <APPLET> tag Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

– Incorporating < APPLET> tag into the Web page


– Creating HTML file
– Testing the applet code

Document shared on [Link]


Building Applet Code
import [Link].*;
import [Link].*;
……
Public class abc extends Applet
{
…..
…..
Public void paint(Graphics g)
{ Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

…..
….. // Applet operation code
…..
}
…..
…..
}

Document shared on [Link]


Building Applet Code ( cont.,)
import [Link].*;
import [Link].*;
Public class abc extends Applet
{
Public void paint(Graphics g)
{
[Link](“Hello Java”,10,100);
} Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

}
When executed draw the string HelloJava at position
10,000(Pixel Value)

Document shared on [Link]


Building Applet Code ( cont.,)
• Chain of classes inherited by Applet class
[Link]

[Link]

[Link]
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

[Link]

[Link]

Document shared on [Link]


Applet Life Cycle

• When an applet is loaded, it under goes a series of changes in


its stage.
• The applet states includes
– Born or initialization State
– Running State
– Idle State Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

– Dead or destroyed Stage


• The changes in state of applet life is shown in the following
state transition diagram.

Document shared on [Link]


Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Applet Life Cycle (cont.,)
Initialization State
• Applet enter this state when it is first loaded.
• This is achieved by calling init() method
• The init() method is the first method to be called.
• Initialize variables in this method.
• This method is called only once during the life time of your
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])
applet

Document shared on [Link]


Running State
• Applet enters into running state when it calls start() method.
• The start() method is called after init().
• It is also called to restart an applet after it has been stopped.
• Where as init() is called only once, start() method may be
called any number of times.
• When a user leaves a web page and come back the applet
resumes execution. Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Idle or Stopped State
• Applet becomes idle when it is stopped.
• Stopping automatically occurs when we leave the page
containing the current applet.
• We can achieve this by calling stop() method.
• Stop() method suspends applet execution until the user clicks
on it.
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Dead State
• Applet is said to be dead when it is removed from memory.
• This occurs by calling destroy() method.
• The destroy() method perform shutdown activities.
• It also removes the applet from the memory.

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Display State
• Applet moves to the display state whenever it has to perform
some output operation on the screen.
• The paint() method is called to accomplish this task.
• Paint() method does absolutely nothing.
• We have to override this method to display the required
graphics.
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Creating An Executable Applet

• Create an html file with <APPLET> tag([Link])

• Create a java code for applet([Link])

• Compile the code and get class file([Link])


Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• Run the html file (By web browser or by appletviewer)

Document shared on [Link]


Designing A Web Page

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Applet Tag
• The <APPLET..> tag supplies the name of the applet to be
loaded and tells the browser how much space the applet
requires.
• The ellipsis in the tag <APPLET..> indicates that it contains
certain attributes that must specified.

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Note
• Name of the applet
• Width of the applet ( in pixel)
• Height of the applet (in pixels)

Document shared on [Link]


Adding Applet To HTML File

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Running The Applet
• We have created applet files as well as the HTML file
containing the applet, we must have the following files in our
current directory:
[Link]
[Link]
[Link]

• To run an applet, we require one of the following tools.


Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• Java - enabled web browser ( such as HotJava or Netscape)


• Java appletviewer

Document shared on [Link]


Running The Applet (cont.,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


More About Applet Tag

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


More About Applet Tag

• Attributes of APPLET Tag

– CODE=[Link]
– CODEBASE=codebase_URL(Optional)
– WIDTH=pixels
– HEIGHT=pixels
– NAME=applet_instance_name(Optional)
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

– ALIGN=alignment(Optional)
– HSPACE=pixels(Optional)
– VSPACE=pixels(Optional)
– ALT=alternate_text(Optional)

Document shared on [Link]


Passing Parameters to Applets

• We can supply user defined parameters to an applet using


<PARAM..> tags
• Each <PARAM..> tag has a name attributes such as color and
value attribute.
• Inside the applet code, the applet can refer to that parameter by
name to find its value
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

• To set up and handle parameters, we need to do two things.


– Include appropriate <PARAM..> tags in the HTML
document
– Provide code in the applet to parse these parameters.

Document shared on [Link]


Passing Parameters to Applets (Cont..,)

• Parameters are passed to an applet when it is loaded. We can


define the inti() method in the applet to get hold of the
parameters defined in the <PARAM..> tags

• This is done using the get Parameter() method, which takes one
string argument representing the name of the parameter and
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

returns a string containing the value of the parameter

Document shared on [Link]


Passing Parameters to Applets (Cont..,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Passing Parameters to Applets (Cont..,)
Run Command
Appletviewer [Link]

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Passing Parameters to Applets (Cont..,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Passing Parameters to Applets (Cont..,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Aligning The Display

• We can align the output of the applet using the ALIGN


attribute. This attribute can have one of the nine value.
» LEFT
» RIGHT
» TOP
» MIDDLE
Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

» ABSMIDDLE
» BASELINE
» BOTTOM
» ABSBOTTOM

Document shared on [Link]


Aligning The Display (Cont..,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Aligning The Display (Cont..,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


More About HTML Tag

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Displaying Numerical Value

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Displaying Numerical Value (Cont.,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Displaying Numerical Value (Cont.,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Getting Input From the User
import [Link].*;
[Link].*;
Public class userinextends Applet
{
TextField text1, text2;
Public void init()
{
text1 = new TextField(8);
text2 = new TextField(8);
add (text1); Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])
add (text2);
[Link](“0”);
[Link](“0”);
}
public void paint(Graphics g)
{
intx=0,y=0,z=0;
String s1,s2,s;
[Link](“Input a number in each box”,10,50);

Document shared on [Link]


try
{
s1=[Link]();
x=[Link](s1);
s2=[Link]();
y=[Link](s2);
}
Catch(Exception ex){}
z=x+y;
s=[Link](z);
[Link](THE SUM IS: “,10,75); Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

[Link](s,100,75);
}
Public Boolean action(Event event, Object obj)
{
repaint();
return true;
}}

Document shared on [Link]


Getting Input From the User (Cont.,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Getting Input From the User (Cont.,)

Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Graphics
Programming Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]


Downloaded by: arthi-krishnakumar (arthykvarshana@[Link])

Document shared on [Link]

You might also like