Difference b/w exceptions and assertions. Define call stack mechanism.
Is it possible to create user define exception. If yes then explain how? Write
a program to print the sum of array using fine-grained exception handling.
Exceptions are the
mechanism used by many programming languages to describe what to do when
something unexpected happens. Typically something unexpected is an error of
some sort, for example when a method is invoked with unacceptable arguments, or
a network connection fails, or the user asks to open a non-existent file.
Assertions are a
way to test certain assumptions about the logic of a program. Assertions are
used to test assumptions about local program logic inside a method, and usually
not to test that external exceptions are met. For example , if we believe that
that at particular point the value of a variable will always be positive, then
an assertion can test this.
Assertions can be
removed entirely from the code when it runs. This make it possible for us to
enable assertions during program development, but to not have the tests
executed at runtime when the final product is delivered.
The java
programming language provides two broad categories of exceptions, known as
checked and unchecked exceptions.
Checked exceptions
are those that the programming is expected to handle in the program, and that
arise from external conditions that can readily occur in a working program.
Example:-- file not found or a network failure.
Unchecked
exceptions might arise from conditions that represent bugs, or situations that
are considered generally too difficult for a program to handle reasonably. They
are called unchecked because we are not required to check for them or do
anything about them if they occur. Exceptions that arise from a category of
situations that probably represent bugs are called runtime exceptions. Example
of runtime exception is attempting to access beyond the end of an array.
Exceptions that
arise as a result of environment issues that are rare enough or hard enough to
recover from are called error. Example:--- running out of memory. Errors are
also unchecked exception.
Call Stack
Mechanism:-
If a statement throws an
exception, and that exception is not handling in the immediately enclosing
method, then that exception is thrown to the calling method. If the exception
is not handled in the calling method, it is thrown to the caller of that
method. This process continues if the exception is still not handled by the
time it gets back to the main() method and main() does not handle it, the
exception terminates the program abnormally.
User- defined
Exceptions:
User-defined exceptions are created by
extending the Exception class. Exception classes contain anything that a
regular class contains.
Public class TestException extends Exception
{
Private int port;
Public TestException(String msg, int port)
{
super(msg);
this.port=port;
}
Public int getPort()
{
Return port;
}
}
//throwing a user defined exception
Public void connect(String serverName) throws
TestException
{
boolean successful;
int portConnect=80;
successful = open(serverName, portConnect);
if(! successful)
{
Throw new TestException(“Could not
connect”,portConnect);
}
}
Write a program to print the sum of array using fine-grained exception handling.
public class Sum
{
Public static void main(String [] args)
{
int add=0;
for(int i=0;i<args.length;i++)
{
try{
add+=Integer.parseInt(args[i]);
}
catch.err.println(“[”+args[i]”]is not an
integer” +”and will not be included in the sum.”);
}
}
System.out.println(“Add=”+add);
}
}
/*this program capture the exception for each
non-integer, command-line argument and generate an warning message. However,
this program proceeds to add all of the valid integer. */
Javac Sum.java
Java sum 1 two 3.0 4
[two] is not an integer and will not be
included in the add.
[3.0] is not an integer and will not be
included in the add.
Add =5.
Draw the hierarchy of AWT package. Explain layout manager.
The java.awt
package is the main package of the AWT, or Abstract Windowing Toolkit. It
contains classes for graphics, including the Java 2D graphics capabilities
introduced in the Java 2 platform, and also defines the basic graphical user
interface (GUI) framework for Java. java.awt also includes a number of
heavyweight GUI objects, many of which have been superseded by the javax.swing
package. java.awt also has a number of important sub packages.
The most important
graphics classes in java.awt are Graphics and its Java 2D extension,
Graphics2D. These classes represent a drawing surface, maintain a set of
drawing attributes, and define methods for drawing and filling lines, shapes,
and text. Classes that represent graphics attributes include Color, Font, Paint,
Stroke, and Composite. The Image class and Shape interface represent things
that you can draw using a Graphics object and the various graphics attributes.
Graphics classes of the java.awt package
The most important
class for GUIs is Component, which represents a single graphical element in a
GUI. Container is a kind of component that can contain other components. The
LayoutManager interface and its various implementations are used to position
components within their containers.
Event, exception, and security classes of the java.awt
package
Basics of Layout Managers
Java technology
uses Layout Managers to define the location and size of Graphical User
Interface components. Java technology does not encourage programmers to use
absolute location and size of components. Java technology instead places
components based on specified Layout Manager. A Layout Manager implements a
layout policy that defines constraints between components in a container.
Types of Layout Managers
Java technology
provides the following Layout Managers, each of which implements the
LayoutManager interface.
·
FlowLayout
·
GridLayout
·
BorderLayout
·
GridBagLayout
·
CardLayout
The FlowLayout is the default Layout Manager for Panel, and hence the Applet class. The BorderLayout is the default Layout Manager for Window class and its subclasses (Frame and Dialog).
Setting Layout Managers
The following
method defined in the Container class can be used for setting layout managers.
void setLayout(LayoutManager mgr);
So for example to set FlowLayout as the Layout Manager for a container C, the following can be used -
C.setLayout(new FlowLayout());
The add method defined in the Container class can be used for adding components to a container. The following are the prototypes of the add method -
Component add(Component comp);
Component add(Component comp, int index);
void add(Component comp, Object constraints, int index);
void add(Component comp, Object constraint);
The order in which components are added to a container effects the placement of components. Also a component added to a container can itself be a container that holds other components.
FlowLayout Manager
FlowLayout places
component in rows from left to right. Components towards the end of row are
written on next row, if there is not enough space in the current row. The
FlowLayout honors the specified size of a component. The size of a component
never changes regardless of size of container. The following constructors of
FlowLayout are provided by AWT -
FlowLayout();
FlowLayout(int alignment);
FlowLayout(int alignment, int hor_gap, int ver_gap);
Alignment can take values of constants - LEFT, CENTER and RIGHT. The default alignment for the components in a row is center. Default horizontal and vertical gaps are 5 pixels.
FlowLayout();
FlowLayout(int alignment);
FlowLayout(int alignment, int hor_gap, int ver_gap);
Alignment can take values of constants - LEFT, CENTER and RIGHT. The default alignment for the components in a row is center. Default horizontal and vertical gaps are 5 pixels.
GridLayout Manager
A GridLayout
Manager places the components in a rectangular grid. Each component's position
is identified by a column and row. All the cells in the grid have same size and
width. Each component is stretched to the cell size. So a GridLayout ignores
the Component's preferred size.
The
GridLayout class provides the following constructors.
GridLayout();
GridLayout(int rows, int columns);
GridLayout(int rows, int columns, int hor_gap, int ver_gap);
This creates a row*col grid layout with the specified horizontal and vertical gaps. In the constructor, either rows or cols can be zero, but not both. The first constructor is equivalent to one row with any number of components. The default gap between components is zero pixels.
GridLayout();
GridLayout(int rows, int columns);
GridLayout(int rows, int columns, int hor_gap, int ver_gap);
This creates a row*col grid layout with the specified horizontal and vertical gaps. In the constructor, either rows or cols can be zero, but not both. The first constructor is equivalent to one row with any number of components. The default gap between components is zero pixels.
BorderLayout
Manager
A BorderLayout
Manager divides the window into five regions - North, East, West, South and
Center. A component can be explicitly added to one of the regions using the
add() method of the Container class. Any space left over by the component in
North, East, South and West is occupied by the component in Center. Only the
last component added to a region is shown, and not all regions need to be
occupied by a component. So a container that uses BorderLayout may have up-to 5
components.
The
BorderLayout class defines the following constructors -
BorderLayout();
BorderLayout(int hor_gap, int ver_gap);
BorderLayout();
BorderLayout(int hor_gap, int ver_gap);
As
illustrated below, components can be added to the container using add() method
defined in the Container class.
Component add(Component comp);
void add(Component comp, Object constraints);
Here constraints can be NORTH, SOUTH, EAST, WEST and CENTER. These constants correspond to strings "North", "South", East", "West", and "Center" respectively. They describe the region where the component should be placed. The default region is CENTER.
Component add(Component comp);
void add(Component comp, Object constraints);
Here constraints can be NORTH, SOUTH, EAST, WEST and CENTER. These constants correspond to strings "North", "South", East", "West", and "Center" respectively. They describe the region where the component should be placed. The default region is CENTER.
GridBagLayout
GridBagLayout is
the most advanced LayoutManager in Java technology.
Comments
Post a Comment