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

Java Programming

Unit-4

Dr. K ADISESHA
Exception Handling 2
& Applets in Java

Introduction

Exception

Exception Handling

Applets Programming

Designing Web Page

Prof. K. Adisesha
3
Introduction

Exception in Java:
An exception (or exceptional event) is a problem that arises during the execution of a
program.
➢ When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
➢ An exception can occur for many different reasons. Following are some scenarios where
an exception occurs.
❖ A user has entered an invalid data.
❖ A file that needs to be opened cannot be found.
❖ A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Prof. K. Adisesha
4
Introduction

Java - Applet:
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
➢ There are some important differences between an applet and a standalone Java application:
❖ An applet is a Java class that extends the java.applet.Applet class.
❖ A main() method is not invoked on an applet, and an applet class will not define main().
❖ Applets are designed to be embedded within an HTML page.
❖ When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
❖ A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or
a separate runtime environment.
❖ The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
Prof. K. Adisesha
5
Exception in Java

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class.
➢ The Exception class and Error is a subclass of the Throwable class.
➢ Errors are abnormal conditions that happen in
case of severe failures, these are not handled
by the Java programs.
➢ The Exception class has two main subclasses:
❖ IOException class
❖ RuntimeException Class.

Prof. K. Adisesha
6
Exception in Java

Types of Java Exceptions:


There are mainly two types of exceptions: checked and unchecked.
➢ An error is considered as the unchecked exception.
➢ However, according to Oracle, there are three types of exceptions namely:
❖ Checked Exception
❖ Unchecked Exception
❖ Error

Prof. K. Adisesha
7
Exception in Java

Types of Java Exceptions:


There are mainly two types of exceptions: checked and unchecked.
➢ Checked Exception: These exceptions cannot simply be ignored, the programmer should
take care of (handle) these exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
➢ Unchecked Exception: The classes that inherit the Runtime Exception are known as
unchecked exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
➢ Error: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Prof. K. Adisesha
8
Exception in Java

Java Exception Keywords:


Java provides five keywords that are used to handle the exception.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether
an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
Prof. K. Adisesha
exception in the method. It doesn't throw an exception. It is always used with method signature.
9
Exception in Java

Exception Handling in Java:


The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
➢ In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
➢ The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application
➢ Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Prof. K. Adisesha
10
Exception Handling in Java

Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords.
➢ A try/catch block is placed around the code that might generate an exception.
➢ Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following. Syntax:
➢ The code which is prone to exceptions is placed in the try {
try block. // Protected code
➢ When an exception occurs, that exception occurred is }
handled by catch block associated with it. catch (ExceptionName e1)
➢ Every try block should be immediately followed either {
// Catch block
by a catch block or finally block.
}
Prof. K. Adisesha
11
Exception Handling in Java
Java try and catch:
When an error occurs, Java will normally stop and generate an error message. The
technical term for this is: Java will throw an exception (throw an error).
➢ The try statement allows you to define a block of code to be tested for errors while it is being
executed.
➢ The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block. Example:
➢ The try and catch keywords come in pairs:. class JavaException
{ public static void main(String args[])
Syntax: try { { int d = 0; int n = 20;
// Block of code to try try { int fraction = n / d;
} System.out.println("This line will not be Executed"); }
catch(Exception e) { catch (ArithmeticException e)
{ System.out.println("In the catch Block due to Exception = " + e);}
// Block of code to handle errors
Prof. K. Adisesha System.out.println("End Of Main"); } }
}
12
Exception Handling in Java

Java Catch Multiple Exceptions:


Java Multi-catch block: A try block can be followed by one or more catch blocks containing a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
➢ At a time only one exception occurs and at a time only one catch block
is executed.
➢ All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Syntax: try { // Block of code to try }
catch(ArithmeticException e) {
// Block of code to handle errors }
catch(Exception e) {
// Block of code to handle errors }
Prof. K. Adisesha
13
Exception Handling in Java

The Throws/Throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
➢ You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Syntax:
➢ throws is used to postpone the handling of a checked exception.
➢ throw is used to invoke an exception explicitly. import java.io.*;
➢ A method can declare that it throws more than one exception, public class className {
public void withdraw(double amount) throws
in which case the exceptions are declared in a list separated RemoteException, InsufficientFundsException
by commas. Syntax: {
public void deposit(double amount) throws // Method implementation
RemoteException { // Method implementation }
throw new RemoteException(); } // Remainder of class definition
Prof. K. Adisesha }
14
Exception Handling in Java

The Finally Block:


The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception. Syntax:
try {
➢ Using a finally block allows you to run any // Protected code
cleanup-type statements that you want to } catch (ExceptionType1 e1) {
execute, no matter what happens in the // Catch block
protected code. } catch (ExceptionType2 e2) {
// Catch block
➢ A finally block appears at the end of the catch
} catch (ExceptionType3 e3) {
blocks and has the following syntax −. // Catch block
}finally {
// The finally block always executes.
}
Prof. K. Adisesha
15
Exception Handling in Java

The Finally Block:


A finally block appears at the end of the catch blocks and has the following Example −
public class ExcepTest
{ public static void main(String args[])
{ int a[] = new int[2];
try { System.out.println("Access element three :" + a[3]); }
catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Exception thrown :" + e); }
finally
{ a[0] = 6;
System.out.println("First element value: " + a[0]); Output:
System.out.println("The finally statement is executed"); } Exception thrown
} :java.lang.ArrayIndexOutOfBoundsException: 3
} First element value: 6
The finally statement is executed
Prof. K. Adisesha
16
Java Applet

Java Applet:
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
➢ An applet is a Java class that extends the java.applet.Applet class.
➢ A main() method is not invoked on an applet, and an applet class will not define main().
➢ Applets are designed to be embedded within an HTML page.
➢ Advantage of Applet
❖ There are many advantages of applet. They are as follows:
❖ It works at client side so less response time.
❖ Secured
❖ It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac OS etc.
Prof. K. Adisesha
17
Java Applet

Java Applet:
Java Applets are programs stored on a web server, similar to web pages:
➢ When an applet is referred to in a web page that has been fetched and processed by a browser,
the browser generates a request to fetch (or download) the applet program, then executes the
program in the browser’s execution context, on the client host.
server host
browser host
web server
browser
reqeust for
myWebPage.html

myWebPage.html
myWebPage.html HelloWorld.class
... request for
<applet code=HelloWorld.class</applet> HelloWorldclass
...
HelloWorld.class HelloWorld.class

Prof. K. Adisesha
18
Java Applet

Applet Execution :
An applet program is a written as a subclass of the java.Applet class or the
javax.swing.Japplet class.
➢ There is no main method: you must override the start method. Applet objects uses AWT for
graphics. JApplet uses SWING.
➢ It is a Grapics object that runs in a Thread object, so every applet can perform graphics, and
runs in parallel to the browser process.
➢ When the applet is loaded, these methods are automatically invoked in order:
❖ The init( ) method is invoked by the Java Virtual Machine.
❖ The start( ) method
❖ The paint( ) method

Prof. K. Adisesha
19
Java Applet
Java Applet:
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
➢ Lifecycle of Java Applet
❖ Applet is initialized.
❖ Applet is started.
❖ Applet is painted.
❖ Applet is stopped.
❖ Applet is destroyed.

Prof. K. Adisesha
20
Java Applet

Lifecycle of Java Applet:


➢ init − This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
➢ start − This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
➢ stop − This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
➢ destroy − This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
➢ paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
Prof. K. Adisesha
21
Java Applet

Applet Life Cycle in Java:


An applet is a Java application executed in any web browser and works on the client-side.
➢ It is created to be placed on an HTML page.
➢ The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
➢ The paint() method belongs to the awt.Component class.
class TestAppletLifeCycle extends Applet { public void stop()
public void init() { // code to stop the applet }
{ // initialized objects } public void destroy()
public void start() { // code to destroy the applet }
{ // code to start the applet } }
public void paint(Graphics graphics)
{ // draw the shapes }
Prof. K. Adisesha
22
Java Applet

The Applet Class:


Every applet is an extension of the java.applet.Applet class. The base Applet class
provides methods that a derived Applet class may call to obtain information and services
from the browser context.
➢ These include methods that do the following −
❖ Get applet parameters
❖ Get the network location of the HTML file that contains the applet
❖ Get the network location of the applet class directory
❖ Print a status message in the browser
❖ Fetch an image
❖ Fetch an audio clip
❖ Play an audio clip
Prof.❖ Resize the applet
K. Adisesha
23
Java Applet

HTML tags for applets :


An applet may be invoked by embedding directives in an HTML file
<APPLET // the beginning of the HTML applet code
CODE="demoxx.class" // the actual name of the applet (usually a 'class' file)
CODEBASE="demos/“ // the location of the applet (relative as here, or a full URL)
NAME=“SWE622" // the name of the instance of the applet on this page
WIDTH="100" HEIGHT="50" // the physical width & height of the applet on the page
ALIGN="Top" // align the applet within its page space (top, bottom, center)
<PARAM //specifies a parameter that can be passed to the applet
NAME=“name1" //the name known internally by the applet in order to receive this parameter
VALUE="000000" the value you want to pass for this parameter > end of this parameter
<PARAM specifies a parameter that can be passed to the applet (applet specific)
NAME=“name2" the name known internally by the applet in order to receive this parameter
VALUE="ffffff" the value you want to pass for this parameter > end of this parameter
</APPLET> specifies the end of the HTML applet code
Prof. K. Adisesha
24
Java Applet

Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
➢ The <applet> tag is the basis for embedding an applet in an HTML file. Following is an
example that invokes the "Hello, World" applet −
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
Prof. K. Adisesha </html>
25
Java Applet

Running an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
➢ There are two ways to run an applet
➢ HTML file: To execute the applet by html file, create an applet and compile it.
❖ After that create an html file and place the applet code in html file.
❖ Now click the html file.
➢ appletViewer tool: To execute the applet by appletviewer tool, create an applet that contains
applet tag in comment and compile it.
❖ After that run it by: appletviewer File.java.

Prof. K. Adisesha
26
Java Applet

Running an Applet:
HTML file: To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html file.
//First.java //myapplet.html
import java.applet.Applet; <html>
import java.awt.Graphics; <body>
public class First extends Applet <applet code="First.class" width="300" height="300">
{ </applet>
public void paint(Graphics g) </body>
{ g.drawString("welcome",150,150); } </html>
}

Prof. K. Adisesha
27
Java Applet

Running an Applet:
Applet by applet viewer tool: To execute the applet by appletviewer tool, create an applet that
contains applet tag in comment and compile it. After that run it by: appletviewer First.java.
//First.java /*
import java.applet.Applet; <applet code="First.class" width="300" height="300">
import java.awt.Graphics; </applet>
public class First extends Applet */
{
public void paint(Graphics g)
{ g.drawString("welcome to applet",150,150); } To execute the applet by appletviewer tool, write in command
prompt:
} c:\>javac First.java
c:\>appletviewer First.java
Prof. K. Adisesha
28
Java Applet
The HelloWorld Applet: public void paint(Graphics g){
<HTML>
<BODY>
final int FONT_SIZE = 42;
<APPLET code=hello.class width=900 height=300> Font font = new Font("Serif", Font.BOLD, FONT_SIZE);
</APPLET>
</BODY> // set font, and color and display message on
</HTML>
// the screen at position 250,150
// applet to display a message in a window
g.setFont(font);
import java.awt.*;
g.setColor(Color.blue);
import java.applet.*;
// The message in the next line is the one you will see
public class hello extends Applet{
g.drawString("Hello, world!",250,150);
public void init( ){
}
setBackground(Color.yellow);
Prof. K. Adisesha
}
}
29
Java Applet
Advanced Applets:
You can use threads in an applet.
➢ You can make socket calls in an applet, subject to the security constraints.
➢ A proxy server can be used to circumvent the security constraints.
Server host Client host Server host Client host
HTTP server browser HTTP server browser

applet download applet download


server Y allowed server Y
connection request applet connection request applet

forbidden Host X
Host X connection request
connection request
server Z
server Z

Prof. K. Adisesha
30
Discussion

Queries ?
Prof. K. Adisesha
9449081542

Prof. K. Adisesha (Ph. D)

You might also like