UNIT-4 c-20
UNIT-4 c-20
Source of errors: Errors are the wrongs that can make a program wrong. Errors may be classified into 2
categories:-
i) Compile time errors
ii) Run time errors
iii) Logical Errors
compile time errors:
These are syntactical errors found in the code, due to which a program fails to compile.
Whenever the compiler displays errors, it will not create the .class file. It is necessary that we correct all
the errors before we can successfully compile and run program.
The most common compile time errors are:
Missing semicolons
Missing (or) mismatch brackets in classes and methods
Misspelling of identifiers and keywords
Missing double codes in strings
Use of undeclared variables
Incompatible type in assignments (or) initialization
Use of equal to in place of double equal to operator etc.
run time errors: These errors represent inefficiency of the computer system to execute a particular
statement. Sometimes a program may compile successfully creating the .class file but may not run properly.
Run-time errors are not detected by the Java compiler. They are detected by the JVM, only at run-time.
//statements
}
When JVM understands that there is an exception, in the try block, then it stores the exception details in
an exception stack and then jumps into a catch block.
catch block: Immediately following the try block includes catch where we should display the exception
details to the user.
Syntax:
catch (ExceptionType variable)
{
A try block and its catch statement form a unit. Remember that every try statement should be followed by at
least one catch statement otherwise compile time error will occur.
finally:
Finally creates a block of code that will be executed after a try/catch block has completed and before the
code following the try/catch block. Cleanup operations code is written inside the „finally‟ block.
The finally block will be executed whether or not an exception is thrown. The finally clause is
optional. Syntax:
finally
{
EXAMPLE: The following program includes a try block and a catch block which process the Arithmetic
Exception generated by the division by zero error.
class A
{
int
d=0;
try
{
int a=42/d;
3
[Link](“not
printed”);
}
catch (ArithmeticException e )
{
throw:
In general, we are catching exceptions that are thrown by java runtime system. However, is possible for our
program throw an exception explicitly, using the throw statement.
catch(NullPointerException ne)
{
Example:
Output:
throws:
A throws clause lists the types of exception that a method may throw. All exception that a method can throw
must be declared in the throws clause.
The general form at a method declaration that includes a throws clause is
Syntax:
type method_name(parameters list) throws Exception list
{
Body of method;
}
Here, Exception list is a comma separated list of the exceptions that a method can throws.
import [Link].*;
class M{
void method()throws IOException{
[Link]("device operation performed");
5
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
[Link]();
[Link]("normal flow...");
}
}
Output:
Most of the times there is possibility of more than one exception present in the program. In this case, the
programmer should write multiple catch blocks to handle each one of them.
In this program, there are 2 – exceptions ArithmenticException and ArrayIndexOutOfBound exception. These
exceptions are handled with the help of 2 catch blocks.
Example:
class edemo {
public static void main (String [] args)
{
try
{
int n=[Link];
[Link]("n="
+n); int a=45/n;
[Link] ("DIVISION VALUE = "+a);
int b[]={10,20,30};
b[50]=100;
}
catch(ArithmeticException Ae)
{
[Link](Ae);
[Link] ("DONT ENTER ZERO FOR DENOMINATOR...");
}
6
catch(ArrayIndexOutOfBoundsException A)
{
[Link](A);
[Link] ("ARRAY INDEX IS OUT OF RANGE..");
}
finally
{
Note: even if there is scope of multiple exceptions, only one exception at a time will occur.
4.6:Explain how to write nested try in exception handling with example:
The try statement can be nested. That is, a try statement can be inside the block of another try. There could
be situations where there is possibility of generation of multiple exceptions of different types with in a particular
block of the program code. We can use nested try statements in such situations. The execution of the corresponding
catch blocks of nested try statements is done using a stack.
Syntax:
try
{
statement 1;
statemen2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
catch(Exception e)
{
....
When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is
7
caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try
block are inspected until all nested try statements are exhausted. If no matching blocks are found, the Java Runtime
Environment handles the execution.
[Link]("normal flow..");
}
8
}
Output:
Built-in Exceptions are the exceptions which are already available in Java. These exceptions are suitable to explain
certain error situations. lists the important Built-in Exceptions.
1) Threads are mainly used in server-side programs to serve the needs of multiple clients on a network (or) internet.
2) Threads are also used to create games &animation. Animation means moving the objects from one place to
another. In many games, generally we have to perform more than one task simultaneously. There threads will be of
invaluable help.
2. Runnable State: If a thread is in this state it means that the thread is ready for execution and waiting for
10
the availability of the processor. If all threads in queue are of same priority then they are given time slots for
execution in round robin fashion.
[Link] State: It means that the processor has given its time to the thread for execution. A thread
keeps running until the following conditions occur.
a. Thread give up its control on its own and it can happen in the following situations.
A thread gets suspended using suspend () method which can only berevived with resume()method.
A thread is made to sleep for a specified period of time using sleep(time) method, where time in
milliseconds.
A thread is made to wait for some event to occur using wait () method. In this case a thread can be
scheduled to run again using notify()method.
b. A thread is pre-empted by a higher priority thread.
4. Blocked State: If a thread is prevented from entering into runnable state
and Sub-sequently running state, then a thread is said to be in Blocked state.
5. Dead State: A runnable thread enters the Dead or terminated state when it completes its task or
otherwise terminates.
Thread methods:
currentThread ():Returns a reference to the currently executing thread object.
yield ():Causes the runtime to context switch from current thread to next available thread.
sleep (int n):Current thread sleeps for n milliseconds.
start (): Used to start a thread. Run () will be called
run (): It is the body of the running thread to be overridden.
stop () : Causes the thread to stop immediately.
setName(string name):Sets the name for the current thread.
getName():Returns the name of the current thread
activeCount():Returns the no of active threads in the current threads groups.
getThreadGroup():Returns the thread group to which this thread belongs.
getState():Returns the state of the thread
getPriority():obtains a thread ‘s priority.
isAlive():determine if a thread is still running.
join():wait for a thread to terminate.
11
Now, the thread will start execution the object of MyClass. In that object, run() method is found, hence it will
execute the statements inside that run() method.
Single thread:
//creating a thread and running it by extending the Thread class
class MyThread extends Thread //step1
{
for(int i=1;i<=100;i++)
{
[Link](i);
}
class ThreadDemo
{
}
Create Thread using Runnable interface
By Implementing Runnable interface:
Easiest way to create a thread is to create class that implements “Runnable” interface which abstracts a unit
of executable code. Then constructs a thread or any object that implements the Runnable.
It includes the following steps to create thread that implements Runnable interface:
1. Create the MyClass that extending the Thread class.
2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute.
3. Create an object to MyClass so that the run () method is available for execution.
4. Now create a thread & attach the thread to the object.
5. Finally Run the Thread by the start( ) method to initiate the thread execution.
//creating a thread and running it by implementing the Runnable interface class MyThread
implements Runnable //step1
{
for(int i=1;i<=100;i++)
{
[Link](i);
}
}
12
}
class ThreadDemo2
{
class ThreadDemo
{
13
{
[Link](“thread B
started”); for (int j=1;j<=4;j++)
{
class MultipleThreads
{
When the threads are created & started a 'thread- scheduler' program in JVM will load them into memory &
execute them. This scheduler will allot more JVM time to those threads which are having higher priorities. The
threads of the same priority are given equal treatment by the java scheduler and, therefore, execute on a FCFS basis.
To set a thread's priority, use the setPriority () method, which is a member of Thread. The general form is.
To get the current priority of a thread, use the getPriority () method of Thread class.
final int getPriority();
Example program:
14
class A extends Thread
{
[Link](“thread B
started”); for (int j=1;j<=4;j++)
{
}
15
class MultipleThreads
{
[Link]([Link]()+1);
[Link](Thread.MIN_PRIORITY);
[Link](“start A “);
[Link]();
[Link](“start B “);
[Link]();
[Link](“start c “);
[Link]();
Output:
start A
start B
start C
thread B is started
thread c is started
Exit form c
Exit form B
thread A is started
from thread A: i= 1;
from thread A: i= 2;
from thread A: i= 3;
from thread A: i= 4;
Exit form A
Synchronized object is like a locked object, locked on a thread. It is a room with only one door. A person has
entered the room & locked from it. The second person who wants to enter the room should wait till the first
person came out.
A thread also locks the object after entering it. Then the next thread can't enter it till the first thread comes out.
This means the object is locked mutually on threads. So, this object is called 'mutex'(mutually exclusive lock).
mutex
How can we synchronize the object? There are 2-ways of doing this.
1) Using synchronized block: -Here, we can embed a group of statements of the object (inside run () method) within
17
a synchronized block, as shown here:
synchronized (object)
//statements;
The statements inside the synchronized block are all available to only one thread at a time. They are not available to
more than one thread simultaneously.
2) Using synchronized keyword:- we can synchronize an entire method by using synchronized keyword. For e g:- if
we went to synchronize the code of display() method, then add the synchronized keyword before the method as show
here.
synchronized void display()
//statements;
wanted=i;
}
synchronized(this)
{
[Link]("Available berths="+available);
if(available>=wanted)
{
String name=[Link]().getName();
[Link](wanted+"berths reserved for"+name); try
{
[Link](1500); available=available-
wanted;
}
18
catch(InterruptedException ie)
{
else
[Link]("sorry no berths");
}
class ThreadSynch
Output:
In some cases, 2 or more threads should communicate with each other. For example consider the classic
queuing problem, where one thread is producing some data and another is consuming it.
Here, polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is
true, appropriate action is taken. This wastes CPU time.
In polling the producer has to wait until the consumer is finished before it generates more data. The
19
consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished,
it would start polling wasting more CPU cycles waiting for the consumer to finish, and so on.
In this way, the producer and consumer can communicate with each other. But this is not an efficient way of
communication. To avoid polling, java includes an elegant inter-process communication mechanism via
wait(),notify(),notifyAll() methods.
1. [Link]():- this method releases an object and sends a notification to a waiting thread that the object is
available.
2. [Link]():- this method is useful to send notifications to all waiting threads that the object is available.
3. [Link]():- this method makes a thread wait for the object till it receives a notification from notify() or
notifyAll() methods.
Note: these methods are used inside the synchronized blocks
Example:
class Buffer{
int a;
boolean produced = false;
//starting threads.
[Link]();
[Link]();
}
}
0utput:
Consumer start consuming...
Producer start producing...
Consumer is waiting...
Product1 is produced.
Producer is waiting...
Product1 is consumed.
Consumer is waiting...
21
Product2 is produced.
Producer is waiting...
Product2 is consumed.
Consumer is waiting...
Product3 is produced.
Producer is waiting...
Product3 is consumed.
Consumer is waiting...
import [Link].*;
class BookTicket extends Thread
{
Object train,comp;
BookTicket(Object train,Object comp)
{
[Link]=train;
[Link]=comp;
}
synchronized(train)
{
[Link]("bookticket is locked by
train"); try
{
[Link](150);
}
catch(InterruptedException e)
{
}
[Link]("bookticket is waiting to lock on compartment");
synchronized(comp)
{
22
}
Object train,comp;
CancelTicket(Object comp ,Object train )
{
[Link]=comp;
[Link]=train;
}
[Link](200);
}
catch(InterruptedException e)
{
}
[Link]("cancel ticket waiting for train ticket object to lock");
synchronized(train)
{
}}}
class ThreadDeadlock
class ThreadResume{
[Link](100);
[Link]();
[Link]("suspending
thread:"+[Link]()); [Link](100);
[Link]();
[Link]("resuming thread
one"); [Link](100);
[Link]();
[Link]("suspending
thread:"+[Link]()); [Link](100);
[Link]();
[Link]("resuming thread two");
24
}
catch(InterruptedException ie)
{
tr
y
{
[Link]("Waiting for threads to finish:");
[Link]();
[Link]();
[Link](" thread one is alive:"+[Link]());
[Link](" thread two is alive:"+[Link]());
catch(InterruptedException ie)
{
Output:
-----------------------------------PREPARED BY [Link]------------------------------------
25