0% found this document useful (0 votes)
34 views

B.SC - III Nep Java Unit-5

This document discusses managing errors and exceptions in Java programs. It describes two types of errors: compile-time errors detected by the compiler, and run-time errors that occur during program execution. Exception handling allows programs to gracefully handle run-time errors. The try-catch block is used to catch exceptions thrown in the try block and take corrective action. Finally blocks are guaranteed to execute regardless of exceptions. Multithreaded programming involves executing multiple threads simultaneously to improve program efficiency.

Uploaded by

kalpanac8090
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)
34 views

B.SC - III Nep Java Unit-5

This document discusses managing errors and exceptions in Java programs. It describes two types of errors: compile-time errors detected by the compiler, and run-time errors that occur during program execution. Exception handling allows programs to gracefully handle run-time errors. The try-catch block is used to catch exceptions thrown in the try block and take corrective action. Finally blocks are guaranteed to execute regardless of exceptions. Multithreaded programming involves executing multiple threads simultaneously to improve program efficiency.

Uploaded by

kalpanac8090
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/ 14

Managing Errors And Exceptions

Introduction
A mistake may lead to causing an error to program to produce unexpected results.
Errors are the wrong that can make program go wrong. An error may produce an incorrect
output or may stop the program execution.

Types Of Errors
Errors may be classified into two types.
 Compile-time errors
 Run-time errors

1. Compile-Time Errors:
All syntax errors will be detected and displayed by Java compiler is called as
compile-time errors. Most of the compile-time errors are due to typing mistakes. Sometimes,
a single error may be the source of multiple errors. For example, use of an undeclared
variable in a number of places will cause a series of errors of type “ undefined variable”. The
some common compile-time errors are
 Missing semicolons.
 Missing (or mismatch) of the brackets in classes and methods.
 Misspelling of identifiers and keywords.
 Missing double quotes in strings.
 Use of undeclared variables
 Incompatible types in assignment / initialization
 Bad references to objects
 Use of = in place of = =operator and etc.,
Whenever the compiler displays, this kinds of error, it will not create the
.class file. It is therefore compulsory to correct all the errors before we cansuccessfully
compile and run the program.

2. Run-Time Errors:
A program may compile successfully creating the .class file but may not run properly. Such
programs may produce wrong results due to wrong logic or stop the program execution due to
errors like
 Dividing an integer by zero.
 Accessing an element that is out of the bounds of an array.
 Trying to store a value into array of an incompatible class or type.
 Trying to cast an instance of a class to one of its subclasses.
 Passing a parameter that is not valid range or value for a method.
 Trying to illegally change the state of a thread.
 Converting invalid string to a number.
 Accessing a character that is out of bounds of a string And etc.,
Exception handling

The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained. Exception
Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

An Exception is an unwanted event that interrupts the normal flow of the program.
When an exception occurs program execution gets terminated. In such cases we get a system
generated error message. The good thing about exceptions is that they can be handled in Java.
By handling the exceptions, we can provide a meaningful message to the user about the issue
rather than a system generated message, which may not be understandable to a user.
The following tasks are used to handling the errors.
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective action (Handle the exception)

The error handling code basically consists of two segments.


 To detect errors and to throw exceptions
 To catch exception and to take appropriate actions.

Syntax Of Exception Handling Code


The basic concepts of exception handling are throwing an exception and catching it as
shown in Fig.4.5.1. Java uses a keyword try to preface a block of code that is likely to cause
an error condition and “ throw “an exception. A catch block defined by the keyword catch
“catches” the exception “thrown” by the try block and handles it appropriately. The catch
block is added immediatelyafter the try block.
The general form is
-
-
try
{
statement; // generates an exception

}
catch ( Exception-type e)
{
statement; // processes the exception
}

The try block can have one or more statements that could generate an exception. If
anyone statement generates an exception, the remaining statements in the block are skipped
and execution jumps to the catch block that is placed next to the try block. The catch block
can have one or more statements that are necessary to process the exception.
Multiple Catch Statements
A single try block can have many catch blocks. This is necessary whenthe try
block has statements that may raise different types of exceptions.
The general form is
-
-
try
{
statement; // generates an exception
}
catch ( Exception-type1 e)
{
statement; // processes the exception type 1
}
catch ( Exception-type2 e)
{
statement; // processes the exception type 2
}
.
.
catch ( Exception-type-N e)
{
statement; // processes the exception type N
}

Java does not require any processing of the exception at all. We cansimply have a
catch statement with empty block to avoid program abortion.

Example:
catch (Exception e); // Does nothing This
statement catches the exception and then ignores it.
Using Finally Statement
Finally statement that can be used to handle any exception generated within a try
block. It may be added immediately after the try block or after the catch block. The general
form is
try try
{ {
-
-
} }
finally catch
{ {
- -
- -
} }
.
.
finally
{

}
When a finally block is defined, this is guaranteed to execute, regardlessof whether
or not in exception is thrown.

Throwing Our Own Exceptions For Debugging


To throw our own exception by using the keyword throw. The generalform is
Throw new Throwable_subclass;
Examples :
throw new ArithmeticException(); throw
new NumberformatException();import
java.lang.Exception;
Multithreaded Programming
Introduction
A thread is small unit of program that is used to perform a particular task. Thusa process can
contain multiple threads. Each thread is used to perform a specific task, which is executed
simultaneously with other threads. The process of executing multiple threads
simultaneously is known as multithreading.

Beginning
class ABC

{
Single–threaded body of execution

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

End

Fig. 4.4.1 Single-threaded program


Every program has at least one thread. If a program contains only one thread, it is called
single threaded program as shown in Fig. 4.4.1. If a program has more than one thread, it
is called multithreaded program as shown in Fig. A Multithreaded program
Main Thread

Main method module

start start start

Switching Switching

Thread A Thread B Thread C

Advantages of Multithreading:
 Multithreading is used to write very efficient programs.
 Maximum use of CPU time ie., the idle time CPU is reduced.
 The time required to perform a context switch from one thread to anotheris less.
 Multithreading require less overheads.
 Multithreading reduces the complexity of large program.
 The resources required for a threads are less than the resources requiredby a
process.
Some Java platform supports the concept of “time slicing”. In time slicing, every thread
receives a small portion of CPU time, which is called a “quantum”. After the time period is
over, even if the thread has not finished its execution, the thread is given no more time to
continue and next thread of equal priority takes the charge of the CPU time. This is the work
of Java scheduler.

Creating Threads
Creating threads in Java is simple. Threads are implemented in the formof objects
that contain a method called run( ).
The general form of run( ) method is
public void run ( )
{
--------------------
--------------------(statements for implementing thread)
--------------------
}
The run ( ) method contains the entire body of the thread an it will beinvoked by an
object of the concerned thread.
A new thread can be created in two ways.
 By creating a thread class.
Create a class that extends Thread class and override its run ( )
method with the code required by the thread.

 By converting a class to a thread.


Define a class that implements Runnable interface, that has only a
run ( ) method .

Starting New Thread

The newly created thread can be started by using start ( ) method. The
general form is
ThreadName ThreadObjectName = new ThreadName( );
ThreadObjectName.start ( ); // invokes run ( ) method

The first statement just creates the object. The thread that will run this object is not
yet running. The thread is in a newborn state. The second statement calls start ( ) method
and thread will move into the ruunable state. Then the Java runtime will schedule the thread
to run by invoking its run ( ) method and thread is to be in the running state.
Life Cycle Of A Thread
The following states can be occurs during the life cycle of a thread. It can move from
one state to another state through a variety of methods as shown in Fig. 4.4.1.
 Newborn state
 Runnable state
 Running state
 Blocked state
 Dead state

New thread
Newborn

start stop

Running Runnable stop Dead


Active thread
killed Killed thread

suspend resume
sleep notify stop
wait

Blocked

Idle thread
(Not Runnable)
Fig. 4.4.1 State transition of a thread
1. Newborn state
A thread is in newborn state immediately after we create a thread object. At this state,
we can do only one of the following things with it. Scheduling of newborn state as shown in
Fig.4.4.2.
 To move the thread into running state using start ( ) method.
 To kill the thread using the stop( ) method.

Newborn

Start stop

Runnable Dead state

Fig. 4.4.2 Scheduling a newborn thread

2. Runnable state
The runnable state means that a thread is ready to run and is a waiting for the control
of the processor. That is, the thread has joined the queue of threads that are waiting for
execution. If one of the thread wants to relinquish control to another thread of equal priority,
then yield ( ) method is used.( see Fig 4.4.3)

yield

running thread runnable thread


Fig. 4.4.3 Relinquishing control using yield ( ) method

3. Running state
Running means the processor has given its time to the thread for its execution. A
running thread may relinquish its control on its own or other higher priority thread in the one
of the following ways.
The thread will be blocked until further order by using suspend( )method. The
blocked thread can be resumed by resume( ) method. This is useful when we want to
suspend a thread for some time due to certain reason,but do not want to kill it. (See Fig
4.4.4)
Suspended

running runnable suspendedresume


Fig. 4.4.4 Relinquishing control using suspend ( ) method
It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep (time) where time is in milliseconds. The thread will return to the
runnable state when the specified time is elapsed. For example, the statement sleep (1000), is
block a thread for 1000 milliseconds. (See Fig 4.4.5)
sleep(time)

running runnable suspended


after( time )

Fig. 4.4.5 Relinquishing control using sleep ( ) method

The thread will be blocked until certain condition occurs by suing wait ( )method. The
notify ( ) method is used to schedule thread to run again. (See Fig.4.4.6)
wait

running runnable waiting


notify
Fig. 4.4.6 Relinquishing control using wait ( ) method

4. Blocked state
A thread is in blocked state, if it is being prevented from the runnable and running
state. This happened when thread is suspended, sleeping, or waiting in order to satisfy certain
requirements. While a thread is in the blocked state, the scheduler will simply skip over it
and no CPU time is allotted, until a thread re-enters the runnable and running state it will not
perform any operation. A blocked thread is considered as “not runnable” but not dead.

5. Dead state
A thread is dead when it finishes its execution (natural death) or is stopped (killed) by
another thread (premature death). A thread can be killed as soon as it born, or while it is
running, or even when it is blocked state.
Synchronization

All the threads in a program share the same memory space. So it is possible for two
threads to access the same variable and methods in an object. Problems may occur when two
or more threads accessing the same data concurrently. The Java enables us to overcome this
problem using a technique iscalled as synchronization.

Synchronization is a process of handling resource accessibility by multiple thread


requests. The main purpose of synchronization is to avoid thread interference. At times when
more than one thread try to access a shared resource, we need to ensure that resource will be
used by only one thread at a time. The process by which this is achieved is called
synchronization. The synchronization keyword in java creates a block of code referred to as
critical section.

The keyword synchronized is used in the code to enable synchronization.


The word ‘synchronized’ can be used along with a method or within a block.
synchronized void update ( )
{
-------------- // code here is synchronized
---------------
}
When declaring a method as synchronized, Java creates a “monitor” and hands it over
to the thread that calls the method first time. As long as the thread contains the monitor, no
other thread can enter the synchronized section of code.

After the work is over, the thread will hand over the monitor to the nextthread that is ready to use the
same resource.
To mark block of code as synchronized as shown below:
synchronized (lock object)
{
-------------- // code here is synchronized
-
}
When two or more threads are waiting to gain control of a resources, due to some
reasons, the condition on which waiting threads to gain control not happened. This situation
is known as deadlock.

For example, assume that the thread X must access MethodA before it can release
MethodB, but the thread Y cannot release MethodA until it gets hold of MethodB. This is the
problem to arises the dead lock.

Thread X
synchronized MethodB ( )
{
synchronized MethodA ( )
{
-------------- // code here is synchronized
-
}
}
Thread Y
synchronized MethodA
{
synchronized MethodB ( )
{
-------------- // code here is synchronized
-
}
}

Runnable Interface
Java runnable is an interface used to execute code on a concurrent thread. It is an
interface which is implemented by any class if we want that the instances of that class should be
executed by a thread.
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. The class must define a method of no arguments called run.

java.lang.Runnable is an interface that is to be implemented by a class whose


instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass
Thread and implement Runnable.

Implementing The Runnable Interface


The Runnable interface declares the run ( ) method that is required for implementing
threads in our program. To do this, we must perform the following steps:
 Declare the class as implementing Runnable interface.
 Implement the run ( ) method.
 Create a thread by defining an object.
 Call the thread’s start ( ) method to run thread.

public void run()

 In this method, we have the code which we want to execute on a concurrent


thread. In this method, we can use variables, instantiate classes, and perform
an action like the same way the main thread does. The thread remains until the
return of this method. The run method establishes an entry point to a new
thread.

To create a thread using runnable, use the following code-

Runnable runnable = new Runnable();


hread thread = new Thread(runnable);
hread.start();
RandomAccess File
This class is used for reading and writing to random access file. A random access
file behaves like a large array of bytes. There is a cursor implied to the array called file
pointer, by moving the cursor we do the read write operations. If end-of-file is reached before
the desired number of byte has been read than EOFException is thrown. It is a type of
IOException.

The RandomAccessFile class supported by the java.io package allows us to create


files that can be used for reading and writing data with random access. That is, we can “jump
around” in the file while using the file. Such files are known as random access files.
A file can be created and opened for random access by giving a mode string as
parameter to the constructor when we open the file. We can use one of the following two
mode strings:
 ‘r’ for reading only
 ‘rw’ for both reading and writing

An existing file can be updated using the ‘rw’ mode. Random access
files support a pointer known as file pointer that can be moved to arbitrary positions
in the file prior to reading or writing. The file pointer is moved using the method seek() in the
RandomAccessFile class.

Example
import java.io.*;
class random
{
public static void main(String args[])
{
try
{
RandomAccessFile raf=new RandomAccessFile("ran.dat","rw");
raf.writeInt(2000);
raf.writeDouble(43.56);
raf.writeBoolean(false);
raf.writeChar('p');
raf.seek(0);
System.out.println(raf.readInt());
System.out.println(raf.readDouble());
System.out.println(raf.readBoolean());
System.out.println(raf.readChar());
}
catch(IOException e)
{}
}
}
O/P is:
C:\>java random
2000
43.56
false
p
How to Use the RandomAccessFile Class

You can create a RandomAccessFile object by supplying the file path as a String or a
File object, plus the access mode:

 public RandomAccessFile(File file, String mode): Creates a randomaccess file


stream to read from, and optionally to write to, the file specified by the File
argument.
 public RandomAccessFile(String name, String mode): Creates a random access
file stream to read from, and optionally to write to, a filewith the specified name.

You might also like