0% found this document useful (0 votes)
39 views

Chapter Two and Exception Handling

An applet is a Java program that runs in a web browser. It overrides methods like init(), start(), stop(), and destroy() from the Applet class. An applet is embedded in an HTML page using the <APPLET> tag. This allows applets to provide dynamic functionality to web pages, such as games, animations, and other interactive content. Unlike Java applications, applets do not have a main() method and are executed by the web browser rather than directly from the command line.

Uploaded by

Abdurezak Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Chapter Two and Exception Handling

An applet is a Java program that runs in a web browser. It overrides methods like init(), start(), stop(), and destroy() from the Applet class. An applet is embedded in an HTML page using the <APPLET> tag. This allows applets to provide dynamic functionality to web pages, such as games, animations, and other interactive content. Unlike Java applications, applets do not have a main() method and are executed by the web browser rather than directly from the command line.

Uploaded by

Abdurezak Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Exception handling

 Java exception is an object that describes an exceptional (error) condition that has occurred in
a piece of code.
 When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error. That method may choose to handle the exception
itself, or pass it on. Either way, at some point, the exception is caught and processed.
Exceptions can be generated by the Java run-time system, or they can be manually generated
by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of
the Java language or the constraints of the Java execution environment. Manually generated
exceptions are typically used to report some error condition to the caller of a method.
 Java exception handling is managed by: try, catch, throw, throws.
 Program statements that you want to monitor for exceptions are contained within a try block.
 If an exception occurs within the try block, it is thrown.
 Your code can catch this exception (using catch) and handle it in some rational manner.
 System-generated exceptions are automatically thrown by the Java runtime system.
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of
the exception class hierarchy. Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches.
 One branch is headed by Exception. This class is used for exceptional conditions that user
programs should catch. This is also the class that you will subclass to create your own custom
exception types.
 There is an important subclass of Exception, called RuntimeException. Exceptions of this type
are automatically defined for the programs that you write and include things such as division by
zero and invalid array indexing.
 The other branch is topped by Error, which defines exceptions that are not expected to be
caught under normal circumstances by your program. Exceptions of type Error are used by
the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack
overflow is an example of such an error.

1
 RuntimeException, Error, and their subclasses are known as unchecked exceptions.
 All other exceptions are known as checked exceptions, meaning that the compiler forces the
programmer to check and deal with them.
 In most cases, unchecked exceptions reflect programming logic errors that are unrecoverable. For
example, an IndexOutOfBoundsException is thrown if you access an element in an array outside
the bounds of the array. These are logic errors that should be corrected in the program. Unchecked
exceptions can occur anywhere in a program. To avoid cumbersome overuse of try-catch blocks,
Java does not mandate that you write code to catch or declare unchecked exceptions.
Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is useful to see what happens when you
don’t handle them. This small program includes an expression that intentionally causes a divide-by-
zero error:
class DivByZero {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a new exception
object and then throws this exception. This causes the execution of DivByZero to stop, because once
an exception has been thrown, it must be caught by an exception handler and dealt with immediately.
In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by
the default handler provided by the Java run-time system. Any exception that is not caught by your
program will ultimately be processed by the default handler. The default handler displays a string

2
describing the exception, prints a stack trace from the point at which the exception occurred, and
terminates the program. Here is the exception generated when the above example is executed:
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Using try and catch
Although the default exception handler provided by the Java run-time system is useful for debugging,
you will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows
you to fix the error. Second, it prevents the program from automatically terminating. Most users would
be confused (to say the least) if your program stopped running and printed a stack trace whenever an
error occurred! Fortunately, it is quite easy to prevent this.
To guard against and handle a run-time error, simply enclose the code that you want to monitor inside
a try block. Immediately following the try block, include a catch clause that specifies the exception
type that you wish to catch. To illustrate how easily this can be done, the following program includes
a try block and a catch clause that processes the ArithmeticException generated by the division-by-
zero error:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

3
Chapter Two: Applet

 An applet is a program, embedded in a Web page and can be run from a browser
 An applet represents byte code embedded in a html page. (applet = bytecode + html) and run
with the help of Java enabled browsers such as Internet Explorer.
 An applet is a Java program that runs in a browser.
 Unlike Java applications applets do not have a main () method.
 To create applet we can use java.applet.Applet or javax.swing.JApplet class.
 All applets inherit the super class ‘Applet’.
 An Applet class contains several methods that helps to control the execution of an applet.
Advantages:
 Applets provide dynamic nature for a webpage.
 Applets are used in developing games and animations.
Creating an applet: Overide the following methods of Applet class.
 public void init ():
 This method is used for initializing variables, parameters to create components.
 This method is executed only once at the time of applet loaded into memory.
 public void start ():
 After init() method is executed, the start method is executed automatically.
 Start method is executed as long as applet gains focus.
 In this method code related to opening files and connecting to database and retrieving
the data and processing the data is written.
 public void stop ():
 This mehtod is executed when the applet loses focus.
 Code related to closing the files and database, stopping threads and performing
cleanup operations are written in this stop method.
 public void destroy ():
 This method is exexuted only once when the applet is terminated from the memory.
 We can also use public void paint (Graphics g) in applets. After writing an applet, an
applet is compiled in the same way as Java application but running of an applet is
different. There are two ways to run an applet.
 Executing an applet within a Java compatible web browser.
 Executing an applet using ‘appletviewer’. This executes the applet in a window.
To execute an applet using web browser, we must write a small HTML file which contains the

4
appropriate ‘APPLET’ tag. <APPLET> tag is useful to embed an applet into an HTML page. It
has the following form:

<APPLET CODE=”name of the applet class file” CODEBASE=”path of the applet class file”
HEIGHT = maximum height of applet in pixels WIDTH = maximum width of applet
in pixels ALIGN = alignment (LEFT, RIGHT, MIDDLE, TOP, BOTTOM)
ALT = alternate text to be displayed>
<PARAM NAME = parameter name VALUE = its value>
</APPLET>

 The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML
page which can be passed to the applet.
 The applet can access the parameter value using getParameter() method, as: String value =
getParameter (“pname”);
Where pname is the parameter name and its value is retrieved.
The HTML file must be saved with .html extension. After creating this file, open the Java
compatible browser (Internet Explorer) and then load this file by specifying the complete path,
then Applet program will get executed.
In order to execute applet program with an applet viewer, simply include a comment at the head
of Java Source code file that contains the ‘APPLET’ tag.Thus, our code is documented with a
prototype of the necessary HTML statements and we can test out compiled applet by starting the
appletviewer with the Java file as: appletviewer programname.java

5
The difference between applet and java application

application Applet
main() method Present main() method Not present
Can be executed on standalone computer system. Used to run a program on client Browser like
(JDK & JRE) Chrome.
Called as stand-alone application as application can Requires some third party tool help like a browser to
be executed from command prompt execute
Application has a single start point which is main Applet application has 5 methods which will be
method automatically invoked.
larger programs Small program
Application do not have Client side / Server side Applets are designed for the client site programming
features purpose

You might also like