0% found this document useful (0 votes)
13 views37 pages

Java Exception Handling and Threading Examples

Uploaded by

rakeshkolupuru9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views37 pages

Java Exception Handling and Threading Examples

Uploaded by

rakeshkolupuru9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Handle exceptions with program :

1st way:

public class TryCatch

public static void main(String[] args)

try {

// Statements in the try block

[Link]("Statement 1");

[Link]("Statement 2");

[Link]("Statement 3");

[Link]("Statement 4");

// The 5th statement that causes a runtime exception

int result = 10 / 0;

// Statements after the exception-causing statement

[Link]("Statement 6");

[Link]("Statement 7");

[Link]("Statement 8");

[Link]("Statement 9");

[Link]("Statement 10");

catch (ArithmeticException e)

// Handling the runtime exception

[Link]("ArithmeticException caught: " + [Link]());

}
// Remaining statements after the catch block

[Link]("Remaining statements after catch block");

Output:

Statement 1

Statement 2

Statement 3

Statement 4

ArithmeticException caught: / by zero

Remaining statements after catch block

2nd way:

import [Link];

public class ThrowsHandling

public static void main(String[] args)

Scanner scanner = new Scanner([Link]);

try

[Link]("Enter a number: ");

int userInput = readUserInput(scanner);

[Link]("You entered: " + userInput);

catch (NumberFormatException e)
{

[Link]("Invalid number format. Please enter a valid number.");

public static int readUserInput(Scanner scanner) throws NumberFormatException

String userInput = [Link]();

return [Link](userInput);

Output:

>java ThrowsHandling

Enter a number: 4

You entered: 4

>java ThrowsHandling

Enter a number: f

Invalid number format. Please enter a valid number.

User Defined Exception :

// Custom exception class

class InvalidAgeException extends Exception

public InvalidAgeException(String message)

super(message);

}
// Class with a method that throws the custom exception

class AgeValidator

public static void validateAge(int age) throws InvalidAgeException

if (age < 0 || age > 120)

throw new InvalidAgeException("Invalid age. Age must be between 0 and 120.");

} else

[Link]("Valid age: " + age);

// Main class to demonstrate the user-defined exception

public class UserException

public static void main(String[] args)

try

// Example usage: try to validate an age

int userAge = -5; // Replace with the user's input

[Link](userAge);

catch (InvalidAgeException e)

[Link]("Exception caught: " + [Link]());


}

Output;

java UserException

Exception caught: Invalid age. Age must be between 0 and 120.

Get the thread priority & set priority


Get the thread name & set the name of the thread

class MyThread extends Thread

public MyThread(String name)

super(name);

public void run()

// Print thread information

printThreadInfo();

public void printThreadInfo()

[Link]("Thread Name: " + getName());

[Link]("Thread Priority: " + getPriority());


[Link]("--------------------------");

public class Threading

public static void main(String[] args)

// Creating threads

MyThread thread1 = new MyThread("Thread 1");

MyThread thread2 = new MyThread("Thread 2");

// Getting and printing initial thread information

[Link]("Initial Thread Information:");

[Link]();

[Link]();

// Setting thread priorities

[Link](Thread.MAX_PRIORITY);

[Link](Thread.MIN_PRIORITY);

// Setting thread names

[Link]("High Priority Thread");

[Link]("Low Priority Thread");

// Getting and printing updated thread information

[Link]("Updated Thread Information:");

[Link]();

[Link]();
// Starting the threads

[Link]();

[Link]();

Output:

Initial Thread Information:

Thread Name: Thread 1

Thread Priority: 5

--------------------------

Thread Name: Thread 2

Thread Priority: 5

--------------------------

Updated Thread Information:

Thread Name: High Priority Thread

Thread Priority: 10

--------------------------

Thread Name: Low Priority Thread

Thread Priority: 1

--------------------------

Thread Name: High Priority Thread

Thread Name: Low Priority Thread

Thread Priority: 1

--------------------------

Thread Priority: 10

11)PRODUCER-CONSUMER PROBLEM SOLVING WITH INTER-THREAD COMMUNCATION


class SharedResource

private int buffer;

private boolean isFull = false;

public synchronized void produce(int item) throws InterruptedException

while (isFull)

wait(); // Wait if the buffer is full

buffer = item;

isFull = true;

[Link]("Produced: " + item);

notify(); // Notify waiting consumers

public synchronized int consume() throws InterruptedException

while (!isFull)

wait(); // Wait if the buffer is empty

int consumedItem = buffer;

isFull = false;

[Link]("Consumed: " + consumedItem);


notify(); // Notify waiting producers

return consumedItem;

class Producer extends Thread

private SharedResource sharedResource;

public void setSharedResource(SharedResource sharedResource)

[Link] = sharedResource;

@Override

public void run()

for (int i = 1; i <= 5; i++)

try

[Link](i);

[Link](1000); // Simulate production time

catch (InterruptedException e)

[Link]().interrupt();

}
class Consumer extends Thread

private SharedResource sharedResource;

public void setSharedResource(SharedResource sharedResource)

[Link] = sharedResource;

@Override

public void run()

for (int i = 0; i < 5; i++)

try

int consumedItem = [Link]();

[Link](1500); // Simulate consumption time

catch (InterruptedException e)

[Link]().interrupt();

public class PCWithITC

public static void main(String[] args)


{

SharedResource sharedResource = new SharedResource();

Producer producerThread = new Producer();

Consumer consumerThread = new Consumer();

[Link](sharedResource);

[Link](sharedResource);

[Link]();

[Link]();

Output:

Produced: 1

Consumed: 1

Produced: 2

Consumed: 2

Produced: 3

Consumed: 3

Produced: 4

Consumed: 4

Produced: 5

Consumed: 5
Inter Thread Communication through Wait () and Notify () methods.

class Rupdate extends Thread


{

int total = 0;

public void run()


{

synchronized(this)
{
for (int i = 1; i < 100; i++)
{
total=total+i;
[Link]();
}
}
}
}
class Interthread
{
public static void main(String[] args) throws InterruptedException
{
Rupdate r=new Rupdate();
[Link]();
synchronized(r)
{
[Link]();
[Link]([Link]);

}
}
}

Output:

>java Interthread
4950

Alive() , sleep() , join() methods :

public class Alive1 extends Thread


{
public void run()
{
for (int i = 0; i < 5; i++)
{
[Link](" child Working...");

}
}

public static void main(String[] args)throws InterruptedException


{
Alive1 t = new Alive1();
// Check if the thread is alive
[Link]("Is the thread alive? " + [Link]());

// Start the thread


[Link]();

for (int i = 0; i < 5; i++)


{
[Link]("main Working...");

}
// Check again after the thread has finished
[Link]("Is the thread alive? " + [Link]());
}
}

Output:
>java Alive1
Is the thread alive? false
main Working...
main Working...
child Working...
child Working...
main Working...
main Working...
main Working...
child Working...
child Working...
Is the thread alive? true
child Working...

class MyThread extends Thread


{
static Thread r;
public void run()

{
for(int i=0;i<5;i++)
{
[Link]("child thread");
try
{

[Link]();
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class JoinThread
{
public static void main(String[] args)throws InterruptedException
{
MyThread.r=[Link]();

MyThread t = new MyThread();


[Link]();
for(int i=0;i<5;i++)
{
[Link]("main thread");
try
{

[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}

Output:

>java JoinThread
main thread
child thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread

public class SleepThread


{

public static void main(String[] args)


{
[Link]("Program started.");

for (int i = 1; i <= 5; i++)


{
[Link]("Countdown: " + i);

try
{

[Link](1000);
} catch (InterruptedException e)
{
[Link]();
}
}
[Link]("Program completed.");
}
}

Output:

>java SleepThread
Program started.
Countdown: 1
Countdown: 2
Countdown: 3
Countdown: 4
Countdown: 5
Program completed.

Creating three threads using the class Thread and then run

class MyThread extends Thread {

public MyThread(String name) {


super(name);
}

public void run() {


for (int i = 1; i <= 5; i++) {
[Link](getName() + ": Count " + i);
try {
[Link](500); // Simulate some work by sleeping
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}

public class ConcurrentThreadExample {


public static void main(String[] args) {
// Creating three threads
MyThread thread1 = new MyThread("Thread A");
MyThread thread2 = new MyThread("Thread B");
MyThread thread3 = new MyThread("Thread C");

// Running threads concurrently


[Link]();
[Link]();
[Link]();
}
}

Output:
>java ThreeThread
Thread A: Count 1
Thread B: Count 1
Thread C: Count 1
Thread A: Count 2
Thread B: Count 2
Thread C: Count 2
Thread A: Count 3
Thread B: Count 3
Thread C: Count 3
Thread A: Count 4
Thread B: Count 4
Thread C: Count 4
Thread A: Count 5
Thread B: Count 5
Thread C: Count 5

three threads using the Runnable interface and then run

class MyRunnable implements Runnable {

private String name;

public MyRunnable(String name) {


[Link] = name;
}

public void run() {


for (int i = 1; i <= 5; i++) {
[Link](name + ": Count " + i);
try {
[Link](500); // Simulate some work by sleeping
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}

public class ConcurrentRunnableExample {


public static void main(String[] args) {
// Creating three Runnable instances
MyRunnable myRunnable1 = new MyRunnable("Thread X");
MyRunnable myRunnable2 = new MyRunnable("Thread Y");
MyRunnable myRunnable3 = new MyRunnable("Thread Z");

// Creating three Thread instances and associating them with Runnable instances
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);

// Running threads concurrently


[Link]();
[Link]();
[Link]();
}
}

Output:

>java ThreeRunnable
Thread X: Count 1
Thread Z: Count 1
Thread Y: Count 1
Thread X: Count 2
Thread Z: Count 2
Thread Y: Count 2
Thread Z: Count 3
Thread X: Count 3
Thread Y: Count 3
Thread X: Count 4
Thread Y: Count 4
Thread Z: Count 4
Thread X: Count 5
Thread Y: Count 5
Thread Z: Count 5
Registration Form With Swing Components :

import [Link].*;

import [Link].*;

import [Link];

import [Link];

public class RegistrationForm extends JFrame {

private JTextField firstNameField, lastNameField, emailField, addressField;

private JPasswordField passwordField;

private JRadioButton maleRadioButton, femaleRadioButton;

private ButtonGroup genderButtonGroup;

private JTextArea displayArea;

public RegistrationForm() {

initializeUI();

private void initializeUI() {

setTitle("Registration Form");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(500, 300);

// Create panels to divide the frame

JPanel inputPanel = new JPanel(new GridLayout(7, 2));

JPanel displayPanel = new JPanel(new BorderLayout());

// Create input fields and labels

JLabel firstNameLabel = new JLabel("First Name:");

JLabel lastNameLabel = new JLabel("Last Name:");


JLabel emailLabel = new JLabel("Email:");

JLabel passwordLabel = new JLabel("Password:");

JLabel genderLabel = new JLabel("Gender:");

JLabel addressLabel = new JLabel("Address:");

firstNameField = new JTextField();

lastNameField = new JTextField();

emailField = new JTextField();

passwordField = new JPasswordField();

addressField = new JTextField();

maleRadioButton = new JRadioButton("Male");

femaleRadioButton = new JRadioButton("Female");

genderButtonGroup = new ButtonGroup();

[Link](maleRadioButton);

[Link](femaleRadioButton);

// Add input fields and labels to the input panel

[Link](firstNameLabel);

[Link](firstNameField);

[Link](lastNameLabel);

[Link](lastNameField);

[Link](emailLabel);

[Link](emailField);

[Link](passwordLabel);

[Link](passwordField);

[Link](genderLabel);

[Link](maleRadioButton);

[Link](new JLabel()); // Empty label for spacing

[Link](femaleRadioButton);

[Link](addressLabel);
[Link](addressField);

// Create display area and add it to the display panel

displayArea = new JTextArea();

[Link](false);

JScrollPane scrollPane = new JScrollPane(displayArea);

[Link](scrollPane, [Link]);

// Create a button to submit the form

JButton submitButton = new JButton("Submit");

[Link](new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

submitForm();

});

// Add components to the frame

getContentPane().setLayout(new GridLayout(1, 2));

getContentPane().add(inputPanel);

getContentPane().add(displayPanel);

getContentPane().add(submitButton);

setLocationRelativeTo(null); // Center the frame

private void submitForm() {

// Get entered data

String firstName = [Link]();

String lastName = [Link]();

String email = [Link]();


char[] passwordChars = [Link]();

String password = new String(passwordChars);

String gender = [Link]() ? "Male" : "Female";

String address = [Link]();

// Display entered data in the text area

String displayText = "First Name: " + firstName + "\n" +

"Last Name: " + lastName + "\n" +

"Email: " + email + "\n" +

"Password: " + password + "\n" +

"Gender: " + gender + "\n" +

"Address: " + address;

[Link](displayText);

public static void main(String[] args) {

[Link](new Runnable() {

@Override

public void run() {

new RegistrationForm().setVisible(true);

});

Output:
Applet total syllabus ( all topics)
Registration Form With AWT Components :

import [Link].*;

import [Link];

import [Link];

public class RegistrationFormAWT extends Frame {

private TextField firstNameField, lastNameField, emailField, addressField;

private TextField passwordField;

private CheckboxGroup genderCheckboxGroup;

private Checkbox maleCheckbox, femaleCheckbox;

private TextArea displayArea;

public RegistrationFormAWT() {

initializeUI();

private void initializeUI() {

setTitle("Registration Form");

setSize(500, 300);

// Create panels to divide the frame

Panel inputPanel = new Panel();

[Link](new GridLayout(7, 2, 5, 5));

Panel displayPanel = new Panel(new BorderLayout());

// Create input fields and labels

Label firstNameLabel = new Label("First Name:");

Label lastNameLabel = new Label("Last Name:");


Label emailLabel = new Label("Email:");

Label passwordLabel = new Label("Password:");

Label genderLabel = new Label("Gender:");

Label addressLabel = new Label("Address:");

firstNameField = new TextField();

lastNameField = new TextField();

emailField = new TextField();

passwordField = new TextField();

addressField = new TextField();

genderCheckboxGroup = new CheckboxGroup();

maleCheckbox = new Checkbox("Male", genderCheckboxGroup, false);

femaleCheckbox = new Checkbox("Female", genderCheckboxGroup, false);

// Add input fields and labels to the input panel

addComponents(inputPanel, firstNameLabel, firstNameField);

addComponents(inputPanel, lastNameLabel, lastNameField);

addComponents(inputPanel, emailLabel, emailField);

addComponents(inputPanel, passwordLabel, passwordField);

addComponents(inputPanel, genderLabel, createGenderPanel());

addComponents(inputPanel, addressLabel, addressField);

// Create a button to submit the form

Button submitButton = new Button("Submit");

[Link](new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

submitForm();

});
// Add components to the display panel

displayArea = new TextArea();

[Link](false);

[Link](displayArea, [Link]);

// Create a panel for the submit button

Panel buttonPanel = new Panel(new FlowLayout([Link]));

[Link](submitButton);

// Add components to the frame

setLayout(new GridLayout(1, 2));

add(inputPanel);

add(displayPanel);

add(buttonPanel);

setLocationRelativeTo(null); // Center the frame

// Handling window close event

addWindowListener(new [Link]() {

public void windowClosing([Link] windowEvent) {

[Link](0);

});

private Panel createGenderPanel() {

Panel genderPanel = new Panel();

[Link](new FlowLayout([Link]));

[Link](maleCheckbox);

[Link](femaleCheckbox);
return genderPanel;

private void addComponents(Panel panel, Component label, Component field) {

[Link](label);

[Link](field);

private void submitForm() {

// Get entered data

String firstName = [Link]();

String lastName = [Link]();

String email = [Link]();

String password = [Link]();

String gender = [Link]() ? "Male" : "Female";

String address = [Link]();

// Display entered data in the text area

String displayText = "First Name: " + firstName + "\n" +

"Last Name: " + lastName + "\n" +

"Email: " + email + "\n" +

"Password: " + password + "\n" +

"Gender: " + gender + "\n" +

"Address: " + address;

[Link](displayText);

public static void main(String[] args) {

RegistrationFormAWT registrationForm = new RegistrationFormAWT();

[Link](true);
}

Output:
Differ Btw AWT and Swing

Delegation event model

Event Classes

EventListener Interfaces

EventListenerInterface Methods

FRAME WITH AWT COMPONENTS:

import [Link].*;

import [Link];

import [Link];

public class FrameExample extends Frame {

private TextField textField;

private TextArea textArea;

private Checkbox checkbox;

private Choice choice;

private List list;

public FrameExample()

// Set layout manager for the frame

setLayout(new FlowLayout());

// Create components
createComponents();

// Set frame properties

setTitle("Frame Example");

setSize(1500, 1200);

setVisible(true);

// Handle window close event

addWindowListener(new [Link]() {

public void windowClosing([Link] windowEvent)

[Link](0);

});

private void createComponents()

// Components for the frame

Button button1 = new Button("Button 1");

textField = new TextField(20);

textArea = new TextArea(10, 30);

[Link](false);

[Link](new Font("Courier New", [Link], 12));

checkbox = new Checkbox("Check Me");

choice = new Choice();

// Add items to choice and list

[Link]("rose");
[Link]("lilly");

[Link]("jasmine");

// Add components to the frame

add(button1);

add(textField);

add(textArea);

add(checkbox);

add(choice);

// Add ActionListener for button1

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

String text = [Link]();

[Link]("Button 1 Clicked: " + text + "\n");

});

// Add ItemListener for checkbox

[Link](e -> {

boolean isChecked = [Link]();

[Link]("Checkbox Checked: " + isChecked + "\n");

});

// Add ItemListener for choice

[Link](e -> {

String selectedOption = [Link]();

[Link]("Choice Selected: " + selectedOption + "\n");


});

public static void main(String[] args) {

new FrameExample();

Output:

MOUSE EVENT: KEYEVENT: WINDOWEVENT:

ACTION EVENT AND INTERFACE: Button , Menu

Layout Mechanisms ALL With Programs

Adapter classes by Example :

Window Adapter , keyadapter , mouse adapter …..

JScrollPane , JSplitPane, JList Programs

Common questions

Powered by AI

AWT (Abstract Window Toolkit) is a low-level UI toolkit for Java, providing system-specific look and feel since it uses the native system's GUI components. Swing, on the other hand, is a part of the Java Foundation Classes (JFC) providing a more flexible and portable GUI component framework built on top of AWT. Swing components, such as JFrame and JButton, are lightweight and provide richer functionality and consistency across platforms compared to AWT components which are heavyweight. Swing components are developed in Java and do not rely on the operating system's GUI as AWT does. Additionally, Swing provides more sophisticated event handling with its model-view-controller architecture, while AWT relies on Java's event delegation model, which is less flexible .

Threading in Java involves creating multiple threads within a single process to execute tasks concurrently. This is crucial for concurrent programming as it allows for efficient resource utilization and improved application performance, especially in tasks that are I/O intensive or can be parallelized. Threads in Java can be implemented using the Thread class or the Runnable interface, offering a way to separate the task execution logic from thread management. Java's thread management includes features like controlling thread execution through methods such as 'start()', 'join()', 'sleep()', and setting thread priorities, which facilitates complex multitasking operations and enhances application responsiveness and throughput .

Thread priorities in Java influence the order in which threads are scheduled for execution. When thread priorities are set using 'setPriority()', higher-priority threads are more likely to be executed before lower-priority threads. For instance, in the example where threads are initially created with default priorities, they are later adjusted such that one has maximum priority and the other has minimum priority. This change indicates that the 'High Priority Thread' is likely to be allocated more CPU time than the 'Low Priority Thread'. However, actual execution behavior can vary depending on the Java Virtual Machine (JVM) and the underlying operating system's thread management policies .

Java Swing components are utilized to create graphical user interfaces (GUIs) allowing user interaction. Components like JTextField for text input, JRadioButton for selectable options, and JButton for actions are combined within a JFrame to construct a form. Event listeners are then attached to these components to handle user actions, such as clicking a button or entering text. For example, an ActionListener can be added to a JButton to trigger the 'submitForm()' method that retrieves data from input fields and displays it in a JTextArea, enabling interactive and reactive user interfaces in Java applications .

Implementing the Runnable interface separates thread logic from thread management, allowing the class to extend another superclass. It is advantageous for providing cleaner design and greater flexibility, particularly in applications requiring multiple inheritance. Extending the Thread class simplifies thread creation by directly associating the task with the thread, beneficial for simple concurrent tasks or when pre-defining thread properties. Both approaches allow running the task using 'Thread.start()', but implementing Runnable is often preferred for its better adherence to Java's single inheritance model, promoting more modular and testable code .

In the 'try-catch' mechanism, a 'try' block encloses code that might throw an exception. If an exception occurs, control is transferred to the 'catch' block. For arithmetic exceptions specifically, when a division by zero occurs, the related code block stops executing, and execution jumps to the 'catch' block where the exception is handled. This allows the program to continue running subsequent code after the catch block, as evidenced when only the first four statements are printed before an ArithmeticException is caught and then 'Remaining statements after catch block' is printed .

In the producer-consumer problem using inter-thread communication, the 'wait()' and 'notify()' methods help manage the synchronization between threads. The 'wait()' method is used to pause the executing thread while 'notify()' or 'notifyAll()' methods are used to wake up waiting threads. When a producer thread adds an item to a full buffer, it invokes 'wait()'. Once the consumer thread consumes an item and the buffer has space, it calls 'notify()' to wake up the waiting producer thread to put more items in the buffer. This ensures that resources are used efficiently without unnecessary busy-waiting .

The 'Alive1' program uses 'isAlive()' to check if a thread is running before and after execution, demonstrating checks on thread life cycle. It confirms the thread's status before starting, showing false, and after it completes, showing true. The 'JoinThread' program illustrates 'join()' by making the 'child' thread wait for the main thread to finish its current loop iteration before continuing, synchronizing execution timing. The 'sleep()' method in both programs, within loops, pauses execution, ensuring orderly output and simulating time-consuming operations without consuming excessive CPU resources .

Custom exception classes in Java extend the existing exception hierarchy to provide more meaningful error descriptions and facilitate better error handling. These classes, such as 'InvalidAgeException', allow developers to define exceptions that are relevant to specific application logic, which can then be caught and processed separately from standard exceptions. By providing specific error messages, as in 'Invalid age. Age must be between 0 and 120', they inform the caller precisely what went wrong and how to address the issue, thus improving code readability and debugging .

The wait-notify mechanism is essential for synchronizing access to shared resources between multiple threads. In Java, it allows threads to communicate efficiently by suspending operations when a resource is unavailable ('wait()') and resuming when conditions are favorable ('notify()' or 'notifyAll()'). Practically, it is crucial in scenarios requiring tight control over thread execution, such as producer-consumer problems. It helps by ensuring a producer doesn't overwrite resources that haven't been consumed yet, and a consumer doesn't read expired or yet-unproduced data, thereby maintaining data integrity and coordination among threads .

You might also like