JAva
JAva
Ans: An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run
time that disrupts the normal flow of the program’s instructions.
EXCEPTION HANDLING
If we want the program to continue with the execution of the remaining code, then we should try to catch the
exception object thrown by the error condition and then display an appropriate message for taking corrective
actions by using below keywords. This task is known as Exception handling.
Types:
1. try: This keyword is used to start a block of code that might raise an exception.
2. except: This keyword is used to catch and handle exceptions that occur within the
corresponding try block.
3. finally: This keyword is used to define a block of code that will always be executed,
regardless of whether an exception occurred in the try block or not.
4. raise: This keyword is used to manually raise exceptions in Python.
5. catch: In some languages like Java, this is used instead of except to catch exceptions.
Try: Syntax
class Ex
{
public static void main(String args[])
{
try
{
System.out.println("open
the files");int n=args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("
a= "+a);
}
catch(ArithmeticException ae)
{
//display the exception details
System.out.println(ae);
System.out.println("please pass
data whilerunning this program");
}
finally
{
//close the files
System.out.println("clos
e files");
}
}
}
O/P: F:\JAVA>javac
exception1.java
F:\JAVA>java Ex
n=0
java.lang.ArithmeticException: / by
zero please pass data while running
this programclose files
b) When a thread exists a monitor, awaiting thread is given the monitor, and can
proceed to access the shared resource associated with this monitor.
Synchronization is easy in java, because all objects have their own implicit
monitor associated with them. To enter an objects monitor, just call a method that
has been modified with the synchronized keyword. While a thread is inside a
synchronized method, all other threads that try to call it on the same instance have
to wait. To exit the monitor and relinquish control of the object to the next waiting
thread, the owner of the monitor simply returns from the synchronized method.
class Callme
{
System.out.print(“[“+ms
g); try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(“Interrupted”);
}
System.out.println(“]”);
}
}
class SyncEx implements Runnable
{
String
msg;
Callme
obj;
Thread t;
SyncEx (Callme ob, String s)
{
Obj=o
b;
msg=s
;
t=new
Thread(this);
t.start();
}
public void run( )
{
obj.call(msg);
}
public static void main(String args[ ])
{
Callme ob =new Callme();
SyncEx ob1=new SyncEx (ob, “Hello”);
SyncEx ob2=new SyncEx (ob,
“Synchronized”); SyncEx ob3=new
SyncEx (ob, “World”);
tr
y
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
catch(InterruptedException e)
{
System.out.println(“Interrupted”);
} }
}
Output :
[Hello]
[Synchr
onized]
[World]
In the above example program if the call( ) method is not
synchronized we can get the mixed output as follows.
[hello[synchronized[world]
]
statement is
snchronized(object){
//statements to be synchronized
}
snchronized(obj)
{
obj.call(msg);
}
}
(b).Explain keyword throws with example?
Syntax:
Return type mehod() throws exception1, exception2, exception3
{
//body of the method
}
Even if the programmer is not handling runtime exceptions, the java
compiler will not give any error related to runtime exceptions. But
the rule is that the programmer should handle checked exceptions.
Incase the programmer does not want to handle the checked
exceptions; he should throw them out using throws clause.
Otherwise, there will be anerror flagged by java compiler
import
java.io.*;
class Sample
{
p
ri
v
a
t
e
S
t
ri
n
g
n
a
m
e
;
v
o
i
d
a
c
c
e
p
t
()
{
BufferedReader
br=new
BufferedReader(new
InputStreamReader(S
ystem.in));
System.out.println("e
nter name: ");
name=br.readLine();
}
void display()
{
System.out.println("Name: "+name);
}
}
class Ex1
{
public static void main(String args[])
{
Samp
le
s=ne
w
Samp
le();
s.acc
ept();
s.display();
}
}
O/P: F:\JAVA>javac
throws.java
throws.java:11: error:
unreported exception
IOException; must be
caught or declared to be
thrown
name=br.readLine();
^
1 error
3.Explain Flow and border layout with example?
Flow layout and border layout are two different layout managers used in graphical user interface
(GUI) development, particularly in Java Swing.
1. Flow Layout:
Flow layout is the default layout manager for many GUI components in Java
Swing.
In a flow layout, components are laid out from left to right, and when the row is
filled, they continue on the next row.
Components are added one after another, without regard for any specific
alignment or arrangement.
It's often used for simple GUIs where you want components to be arranged in a
natural order as they're added.
To use flow layout, you can either specify it explicitly when adding components to
a container or rely on its default behavior.
2. Border Layout:
Border layout is another layout manager in Java Swing that divides the container
into five regions: north, south, east, west, and center.
Components are added to one of these regions and are resized to fill the
available space in that region.
The "center" region takes up the remaining space in the container after the other
regions have been filled.
Border layout is useful for creating more structured GUIs where you want certain
components to occupy specific areas of the container, such as having a menu bar
at the top (north), a status bar at the bottom (south), and main content in the
center.
You can explicitly specify the region when adding components to a container
using border layout.
import javax.swing.*;
import java.awt.*;
public class LayoutExample extends JFrame {
public LayoutExample() {
setTitle("Layout Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null); // Center the frame
}
An applet is a small Java program that runs within a web browser. Applets are
typically embedded in web pages and provide interactive and dynamic content to
users. They were popular in the early days of the internet for creating animations,
games, simulations, and other interactive content.
import java.applet.Applet;
import java.awt.*;
@Override
// Initialization code
@Override
// Start code
@Override
// Stop code
}
@Override
// Cleanup code
@Override
// Rendering code