The document provides information about exceptions and applets in Java. It discusses exception handling in Java, including checked and unchecked exceptions. It also covers the try, catch, throw and throws keywords used in exception handling. Additionally, it describes applets in Java, including how applets extend the Applet class, their lifecycle through init(), start(), stop() and destroy() methods, and how to invoke an applet through HTML tags.
3. Introduction
Prof. K. Adisesha
3
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.
4. Introduction
Prof. K. Adisesha
4
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.
5. Exception in Java
Prof. K. Adisesha
5
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.
6. Exception in Java
Prof. K. Adisesha
6
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
7. Exception in Java
Prof. K. Adisesha
7
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.
8. Exception in Java
Prof. K. Adisesha
8
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
exception in the method. It doesn't throw an exception. It is always used with method signature.
9. Exception in Java
Prof. K. Adisesha
9
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.
10. Exception Handling in Java
Prof. K. Adisesha
10
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:
try {
// Protected code
}
catch (ExceptionName e1)
{
// Catch block
}
➢ The code which is prone to exceptions is placed in the
try block.
➢ When an exception occurs, that exception occurred is
handled by catch block associated with it.
➢ Every try block should be immediately followed either
by a catch block or finally block.
11. Exception Handling in Java
Prof. K. Adisesha
11
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.
➢ The try and catch keywords come in pairs:.
Syntax: try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Example:
class JavaException
{ public static void main(String args[])
{ int d = 0; int n = 20;
try { int fraction = n / d;
System.out.println("This line will not be Executed"); }
catch (ArithmeticException e)
{ System.out.println("In the catch Block due to Exception = " + e);}
System.out.println("End Of Main"); } }
12. Exception Handling in Java
Prof. K. Adisesha
12
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.
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 }
➢ 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.
13. Exception Handling in Java
Prof. K. Adisesha
13
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:
import java.io.*;
public class className {
public void withdraw(double amount) throws
RemoteException, InsufficientFundsException
{
// Method implementation
}
// Remainder of class definition
}
➢ throws is used to postpone the handling of a checked exception.
➢ throw is used to invoke an exception explicitly.
➢ A method can declare that it throws more than one exception,
in which case the exceptions are declared in a list separated
by commas. Syntax:
public void deposit(double amount) throws
RemoteException { // Method implementation
throw new RemoteException(); }
14. Exception Handling in Java
Prof. K. Adisesha
14
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 {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
➢ Using a finally block allows you to run any
cleanup-type statements that you want to
execute, no matter what happens in the
protected code.
➢ A finally block appears at the end of the catch
blocks and has the following syntax −.
15. Exception Handling in Java
Prof. K. Adisesha
15
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]);
System.out.println("The finally statement is executed"); }
}
}
Output:
Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
16. Java Applet
Prof. K. Adisesha
16
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.
17. Java Applet
Prof. K. Adisesha
17
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.
<applet code=HelloWorld.class</applet>
...
...
HelloWorld.class
server host
web server
myWebPage.html
browser host
browser
reqeust for
myWebPage.html
myWebPage.html
request for
HelloWorldclass
HelloWorld.class
HelloWorld.class
18. Java Applet
Prof. K. Adisesha
18
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
19. Java Applet
Prof. K. Adisesha
19
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.
20. Java Applet
Prof. K. Adisesha
20
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.
21. Java Applet
Prof. K. Adisesha
21
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 init()
{ // initialized objects }
public void start()
{ // code to start the applet }
public void paint(Graphics graphics)
{ // draw the shapes }
public void stop()
{ // code to stop the applet }
public void destroy()
{ // code to destroy the applet }
}
22. Java Applet
Prof. K. Adisesha
22
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
❖ Resize the applet
23. Java Applet
Prof. K. Adisesha
23
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
24. Java Applet
Prof. K. Adisesha
24
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>
</html>
25. Java Applet
Prof. K. Adisesha
25
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.
26. Java Applet
Prof. K. Adisesha
26
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
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{ g.drawString("welcome",150,150); }
}
//myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
27. Java Applet
Prof. K. Adisesha
27
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;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{ g.drawString("welcome to applet",150,150); }
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command
prompt:
c:>javac First.java
c:>appletviewer First.java
28. Java Applet
Prof. K. Adisesha
28
The HelloWorld Applet:
<HTML>
<BODY>
<APPLET code=hello.class width=900 height=300>
</APPLET>
</BODY>
</HTML>
// applet to display a message in a window
import java.awt.*;
import java.applet.*;
public class hello extends Applet{
public void init( ){
setBackground(Color.yellow);
}
public void paint(Graphics g){
final int FONT_SIZE = 42;
Font font = new Font("Serif", Font.BOLD, FONT_SIZE);
// set font, and color and display message on
// the screen at position 250,150
g.setFont(font);
g.setColor(Color.blue);
// The message in the next line is the one you will see
g.drawString("Hello, world!",250,150);
}
}
29. Server host Client host
HTTP server browser
applet
Host X
applet download
connection request
connection request
forbidden
allowed
server Y
server Z
Java Applet
Prof. K. Adisesha
29
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
HTTP server browser
applet
Host X
applet download
connection request
server Y
server Z
connection request