0% found this document useful (0 votes)
4 views25 pages

Unit-Iii Java-1

This document covers the fundamentals of exception handling and multithreading in Java, including types of exceptions, models of exception handling, and the Java thread model. It explains how to use try-catch blocks, multiple catch clauses, and the significance of the finally block, as well as the differences between thread-based and process-based multitasking. Additionally, it provides examples of creating threads and handling exceptions effectively.

Uploaded by

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

Unit-Iii Java-1

This document covers the fundamentals of exception handling and multithreading in Java, including types of exceptions, models of exception handling, and the Java thread model. It explains how to use try-catch blocks, multiple catch clauses, and the significance of the finally block, as well as the differences between thread-based and process-based multitasking. Additionally, it provides examples of creating threads and handling exceptions effectively.

Uploaded by

Vinay Vinnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT - III

Exception handling - Fundamentals of exception handling, Exception types,


Termination or Resumptive models, uncaught exceptions, using try and catch,
multiple catch clauses, nested try statements, throw, throws and finally, built-
in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-
based multitasking, Java thread model, creating threads, thread priorities,
synchronizing threads, Inter thread communication.

Fundamentals of exception handling:


An error in a program is called bug. The process of removing the errors is
called debugging.
There are two types of errors in java.
1) Compile time errors
2) Run Time errors.

Compile time errors: These are syntactical errors found in the code, due to
which a program fails to compile for example, forgetting a semicolon(;) at the
end of a java statement or writing a statement without proper syntax will result
in compile time error.

Run Time errors: All logical errors are called runtime errors (or) these are the
errors happen at runtime because of inefficiency of computer system. All run
time errors are detected by JVM.

Hierarchy of Exception classes


Exception types:
Exception: An exception is a runtime error
Types of exceptions:
There are mainly two types of exceptions
1. Checked Exceptions
2. Unchecked Exceptions

Checked Exceptions: The Exceptions that are checked at compile time by the
java compiler are called checked exceptions
Ex: No such method Exception
Class not found exception
Unchecked Exceptions: The Exceptions that are checked by the JVM at run
time are called Unchecked Exceptions.
Ex: ArithmeticException.
ArrayIndexOutOfBoundsException.

Termination or Resumptive models

TerminationModel

In termination model the code after the point at which exception occurs (throw
point) will not be executed. That means execution is terminated at that point at
which exception occurs.
The termination Model works as follows:
1. The exception is thrown
2. Try block has expired.
3. Flow of control proceeds, it is transferred to the nearest exception handler
that can handle the type of exception encountered.
4. Program control does not return to throw point.

Resumptive Model:

The resumptive model is a model in which exception handler will try to clean
up the environment caused from exception and will try to restart the exception.

1.The exception is thrown


2.The exception is handled using handler
3.The control is transferred to the point next to the one where the execution
flow was interrupted because of the exception and the execution continues
from there on.
4.When the control is returned a clean environment will be provided to the
programmer.
Uncaught Exceptions in Java

In java, assume that, if we do not handle the exceptions in a program. In this


case, when an exception occurs in a particular function, then Java prints a
exception message with the help of uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the
compiler but automatically caught and handled by the Java built-in exception
handler.
Java programming language has a very strong exception handling mechanism.
It allow us to handle the exception use the keywords like try, catch, finally,
throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the
exception occurs and terminates the thread.
The Division by zero exception is one of the examples for uncaught exceptions.
Look at the following code.

import java.util.*;
public class UncaughtExceptionExample
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);

}
}
When we execute the above code, it produce the following output for the value
a = 10 and b = 0.
Using try and catch:

When there is an exception the program will be terminated abnormally in the


middle. Any subsequent statements are not executed so the user may lose
data. To prevent this we should perform the following steps

Step 1. The programmer should observe the statements in his program where
there may be a possibility of exceptions such statements should be written
inside a try block.

Syntax:
try{
Statements;
}
Step 2.The programmer should write the catch block where he should display
the exception details to the user.This helps the user to understand that there is
some error in the program.The programmer should also display amessage
regarding what can be done to avoid this error.

Syntax:
catch(Exceptionclass ref)
{
Statements;
}
Example:
Import java.lang.*;
class Simple
{
public static void main(String args[])
{
try{
int data=50/0;
System.out.println(“data is”+data);
}catch(ArithmeticException e)
{
System.out.println(“divide by zero error”);
}
System.out.println("rest of the code...");
}
}
Output:
divide by zero error
rest of the code...
Multiple catch Blocks:

In some cases more than one exception could be raised by a single piece
of code .To handle this type of situation you can specify two or more catch
statements. Each catching a different type of exception.
Syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}

Example:
class multexce
{
public static void main(String[] args)
{
int a=0;
try
{
int b=42/a;
int c[]={1};
c[50]=99;
}
catch (ArithmeticException e)
{
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae);
}
}
}
Nested try statements

A try block is placed inside the block of another try block is termed as
nested try block statements

Syntax:

try
{
statement 1;
statement 2;

try
{
statement 1;
statement 2;
}

catch(Exception e)
{
}
}
catch(Exception e)
{
}

Example:

import java.lang.*;
class NTDemo
{
public static void main(String[] args)
{
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c;
try
{
c=a/b;
System.out.println("result is"+c);
}
catch (ArithmeticException e)
{
System.out.println("Divide by zero error");
}
}
catch (NumberFormatException e)
{
System.out.println("Incorrect type of data");
}

}
}
Output:
C:\>javac NTDemo.java

C:\>java NTDemo 10 0
Divide by zero error

C:\>java NTDemo 10 b
Incorrect type of data

Finally
The finally block is a block that is always executed. It is mainly used to perform
some important tasks such as closing connection, stream etc.
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.
}
Example:

class Simple
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println(“welcome to exception handling");
}
System.out.println("rest of the code...");
}
}
Throw/Creating own exception sub classes.

The throw keyword is used to explictily throw an exception. We can throw


either checked or uncheked exception. The throw keyword is mainly used to
throw a user defined exception

Syntax is:

throw throwableInstance;

Example:

import java.lang.*;
class myown extends Exception
{
myown(int bal)
{
System.out.println("insufficient balanace"+bal);
}
}
class userexceDemo
{
public static void main(String args[])
{
try
{
int bal=400;
if(bal<500) throw new myown(bal);
else
System.out.println("transaction is allowed");
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
}
}
Output:
C:\NCM>javac userexceDemo.java

C:\NCM>java userexceDemo
insufficient balanace400
Exception occured: myown

Throws
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.

Syntax of throws keyword:

void method_name()throws exception_class_name


{
... //body of the method
}

Example:

import java.lang.*;
import java.io.*;
class ThrowsDemo
{
public static void main(String args[]) throws Exception
{
int a,b,c;
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));
System.out.println("Enter a value");
a=Integer.parseInt(br.readLine());
System.out.println("Enter b value");
b=Integer.parseInt(br.readLine());
c=a/b;
System.out.println("Division is"+c);
}
}
Output:

C:\NCM>javac ThrowsDemo.java

C:\NCM>java ThrowsDemo
Enter a value
30
Enter b value
6
Division is5

Difference between throw and throws:


Built- in exceptions

Built in Exceptions are the exceptions which are available in Java. These
Exceptions are suitable to explain error situations. Important built in
exceptions are.

Exception class Meaning


Thrown when an exception condition has
ArithmeticException occurred in an arithmetic operation.

Thrown to indicate that an array has been


ArrayIndexOutOfBoundsException accesses with an illegal index.

This exception is raised when we try to


access a class whose definition is not
ClassNotFoundException found.

Raised when a file is not accessible or does


FileNotFoundException not open.

Thrown when an input-output operation


IOException failed or interrupted.

Thrown when a thread is waiting, sleeping


or doing some processing, and it is
InterruptedException interrupted.

Thrown when a class does not contain the


NoSuchFieldException field (or variable) specified.

Thrown when accessing a method which is


NoSuchMethodException not found.

Raised when referring to the members of a


NullPointerException null object.

Raised when a method could not convert a


NumberFormatException string into numeric format.

This represents any exception which


RunTimeException occurs during runtime.

Thrown by string class methods to indicate


that an index is either negative or greater
StrinIndexOutOfBoundsException than the size of the string
Multithreading:

A multithreaded program contains two or more parts that can run


concurrently. Each part of such program is called thread and each thread
defines a separate path of execution. Multithreading is a specialized form of
multitasking

Multitasking
Multitasking is the feature that allows the computer to run two or more
programs concurrently.

Types of multitasking
Process-based
Thread-based

Process-based
A process is a program in execution. Process based multitasking is the
feature that allows your computer to run two or more programs concurrently.
For ex process based multitasking enables you to run the java compiler at the
same time that you are using a text editor. In process based multitasking, a
program is the smallest unit of code that can be dispatched by the scheduler

For ex priority scheduling


 PROCESS BURSTTIME PRIORITY
 P1 10 2
 P2 01 4
 P3 02 2
 P4 01 1
 P5 05 3

Thread based
In a thread based multitasking environment, the thread is the smallest
unit of dispatchable code. This means that a single program can perform two or
more tasks simultaneously. For instance, a text editor can format text at the
same time that it is printing, as long as these two actions are being performed
by two separate threads. Thus process based multitasking deals with the big-
picture, and thread based multitasking handles the details.
Differences between thread-based multitasking and process-based
multitasking
Multithreading Multiprocessing
1.Thread is a fundamental unit of 1.Programor process is a fundamental
multithreading unit of multiprocessing environment.
2.Multiple parts of a single program 2.Multiple programs get executed in
gets executed in multithreading multiprocessing environment.
environment.
3.During multithreading the processor 3.During multiprocessing the
switches between multiple threads of processor switches between multiple
the program programs or processors.
4.It is cost effective because CPU can 4.It is expensive because when a
be shared among multiple threads at a particular process uses CPU other
time. processes has to wait.
5.It is high efficient 5.It is less efficient in comparison with
multithreading.
6.It helps in developing efficient 6.It helps in developing efficient
application programs operating system programs.

Java Thread Model

1.The thread that was just created is in the born state.

2.The thread remains in this state until the threads start method is called. This
causes the thread to enter the ready state

3.The highest priority ready thread enters the running state when the system
assigns a processor to the thread i.e., the thread begins executing.

4.When running thread calls wait the thread enters into a waiting state for the
particular object on which wait was called. Every thread in the waiting state for
a given object becomes ready on a call to notify all by another thread
associated with the object.
5.When a sleep method is called in a running thread that thread enters into the
suspended (sleep) state. A sleeping thread becomes ready after the designated
sleep time expires. A sleeping thread cannot use a processor even if one is
available.

6.A thread enters the dead state when its run() method complete or terminates
for any reason.

7.One common way for running thread to enter the blocked state is when the
thread issues an input or output waits for completes. A blocked thread can’t
use processors even if one is available.

Thread Constructors
Thread()
Thread(String ThreadName)
Thread(Runnable obj)
Thread( Runnable obj,String Name)
Thread(ThreadGroup tg,String ThreadName)

Thread Methods
String getNames() : it obtain the names of the Thread
void setName (String str): it sets the name of the thread.
int getPriority(): it obtains the priority of the thread.
void setPriority(): it sets the priority of the thread.
boolean is Alive(): Determines if a thread is still running or not
void sleep(long milliseconds) Suspend a thread for a period of time
void start(): Start a thread by calling its run method
void run(): It defines the code that constitutes the new thread. Whenever the
start() method executes it automatically call of run() method
void join(): this method waits until the thread on which it is called terminates
Thread currentThread(): it returns a reference to the currently executing
Thread.
void yield(): A thread can call the yield method to give other threads a chance to
execute.
ThreadGroup getThreadGroup(): It returns the name of the thread group which
contains currently running thread.
Main Thread
When a java program starts up,one thread begins running immediately.This
one is main thread,which is created by virtual machine.it is executed in the
program for first time.It must be the last thread to finish execution.

Creating Threads
Step1:create a class that extends thread class or implements runnable
interface.
Ex: class MyThread extends Thread
Step2: Write public void run() method with body.
Step3:create an object to the class and attach a thread to it.
Ex: MyThread m=new MyThread();
Thraed t=new Thread(m);
Step4:start the thread by using start() method
t.start();

A thread can be created in two ways


1. Extending the thread class
2. Implementing the runnable interface

1.Extending the Thread Class

Example:
import java.lang.*;
class MyThread extends Thread
{
public void run()
{
System.out.println("Welcome to VAAGESWARI");
}
}
class ThreadEx1
{
public static void main(String args[] )
{
MyThread m = new MyThread();
Thread t=new Thread(m);
t.start();
}
}
Output: Welcome to VAAGESWARI
2. Implementing the runnable interface
Example:
import java.lang.*;
class MyThread implements Runnable
{
public void run()
{
System.out.println("welcome to VAAGESWARI");
}
}
class ThreadEx2
{
public static void main(String args[] )
{
MyThread m = new MyThread();
Thread t=new Thread(m);
t.start();
}
}
Output: Welcome to VAAGESWARI

Example 2:
import java.lang.*;
class MyThread implements Runnable
{
public void run()
{
add();
sub();
}
void add()
{
int a,b,c;
a=10;b=20;
c=a+b;
System.out.println("sum is"+c);
}
void sub()
{
int a,b,c;
a=34;b=23;
c=a-b;
System.out.println("sub value is"+c);
}
}
class ThreadEx3
{
public static void main(String args[] )
{
MyThread m = new MyThread();
Thread t=new Thread(m);
t.start();
}
}
Output:
C:\>javac ThreadEx3.java

C:\>java ThreadEx3
sum is30
sub value is11

Thread Priorities:
When the threads are created and started, a thread scheduler program in JVM
will load them into memory and execute them. This scheduler will allot more
JVM time to those threads which are having higher priorities. Priorities are
represented by a number between 1 and 10. In most cases, thread scheduler
schedules the threads according to their priority (known as preemptive
scheduling).
The three priority constants defined in Thread class are:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY
is 1 and the value of MAX_PRIORITY is 10.

Example:
import java.lang.*;
class MyThread1 extends Thread
{
public void run()
{
add();
}
void add()
{
int a,b,c;
a=10;b=20;
c=a+b;
System.out.println("sum is"+c);
}
}
class MyThread2 extends Thread
{
public void run()
{
sub();
}
void sub()
{
int a,b,c;
a=10;b=20;
c=a-b;
System.out.println("sub is"+c);
}
}
class MyThread3 extends Thread
{
public void run()
{
mul();
}
void mul()
{
int a,b,c;
a=10;b=20;
c=a*b;
System.out.println("mul is"+c);
}
}

class ThreadPDemo
{
public static void main(String args[] )
{
MyThread1 m1 = new MyThread1();
Thread t1=new Thread(m1);
MyThread2 m2 = new MyThread2();
Thread t2=new Thread(m2);
MyThread3 m3 = new MyThread3();
Thread t3=new Thread(m3);
t1.setPriority(2);
t2.setPriority(1);
t3.setPriority(3);
t1.start();
t2.start();
t3.start();
}
}
Output:

C:\>java ThreadPDemo
sub is-10
sum is30
mul is200

Synchronizing Threads:
When a thread is already acting on an object, preventing any other thread from
acting on the same object is called “Thread Synchronization or thread safe. The
object on which the threads are synchronized is called synchronized object.
Thread synchronization is recommended when multiple threads are used on
the same object.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent.
Let's see the example:

Class Table
{
void printTable(int n)//method not synchronized
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class Use
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
Solution by synchronized method
If you declare any method as synchronized, it is known as synchronized
method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the
lock for that object and releases it when the method returns.
Class Table
{
synchronized void printTable(int n)//synchronized method
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class Use
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500

Inter-thread communication
Cooperation (Inter-thread communication) is a mechanism in which a thread is
paused running in its critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed.

It is implemented by following methods of Object class:

wait()
notify()
notifyAll()

1) wait() method
Causes current thread to release the lock and wait until either another thread
invokes
the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.

Method
public final void wait()throws InterruptedException: waits until object is
notified.
public final void wait(long timeout)throws InterruptedException:waits for the
specified amount of time.

2) notify() :method Wakes up a single thread that is waiting on this object's


monitor. If any threads are waiting on this object, one of them is chosen to be
awakened.

The choice is arbitrary and occurs at the discretion of the implementation.


Syntax:
public final void notify()

3) notifyAll() method Wakes up all threads that are waiting on this object's
monitor.

Syntax:
public final void notifyAll()

Write a Java program that correctly implements the producer – consumer


problem using the concept of inter thread communication

import java.lang.*;
class Q
{
int n;
boolean busy=false;
synchronized int get()
{
if(!busy)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
busy=false;
notify();
return n;
}
synchronized void put(int n1)
{
if(busy)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
n=n1;
busy=true;
System.out.println("Put:"+n);
notify();
}
}

class Producer implements Runnable


{
Q q;
Producer(Q q1)
{
q=q1;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}

class Consumer implements Runnable


{
Q q;
Consumer(Q q2)
{
q=q2;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}

class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
System.out.println("Press Control-c to stop");
}
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy