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

Unit3_Exception handling & Multithreading

Chapter 3 of the Java Programming document covers Exception Handling and Multithreading. It explains the types of errors (compile-time and runtime), the concept of exceptions, and how to handle them using try-catch blocks, finally blocks, and user-defined exceptions. Additionally, it introduces multithreading, its advantages, and methods for creating threads in Java.

Uploaded by

ketankotane552
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Unit3_Exception handling & Multithreading

Chapter 3 of the Java Programming document covers Exception Handling and Multithreading. It explains the types of errors (compile-time and runtime), the concept of exceptions, and how to handle them using try-catch blocks, finally blocks, and user-defined exceptions. Additionally, it introduces multithreading, its advantages, and methods for creating threads in Java.

Uploaded by

ketankotane552
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

333

Java Programming (314317) Chapter-3

Chapter 3
Marks-12
Exception handling & Multithreading

4.1 Errors & Exception


Types of Error
Errors can be categorized in two types:-
1. Compile time errors
2. Runtime errors

1. Compile Time Error


• All syntax errors will be detected and displayed by java compiler.
• These errors are known as compile time errors.
• For eg:
– Missing semicolon
– Missing (or mismatch of) bracket in classes & methods
– Misspelling of identifiers & keywords
– Missing double quotes in string
– Use of undeclared variables.

2. Run Time Error


• A program may compile successfully but may not run properly.
• Programs may terminate due to errors . Then java generates an error message and aborts the
program.
• For eg:
– Dividing an integer by zero
– Accessing an element that is out of bounds of an array
– Trying to illegally change status of thread
– Attempting to use a negative size for an array
– Converting invalid string to a number

Exception
• Exception is an abnormal condition.
• An Exception is a condition that is caused by a run-time error in the program.
• When java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object and throws it.
• An Exception interrupts the normal flow of the program.
• When an exception occurs program gets terminated abnormally.
• In such cases system generated error messages are displayed.
• Exceptions can be handled.
• Exception can occur at runtime (known as runtime exceptions) as well as at compile-time
(known Compile-time exceptions).

1
333
Java Programming (314317) Chapter-3

• Reasons for Exceptions


– Opening a non-existing file
– Network connection problem
– Using array index out of limit
– Divide by zero
– Attempting to use a negative size for an array
– Converting invalid string to a number

❖ List of some Built-in exceptions:


• ArithmeticException
• ArrayIndexOutOfBoundsException
• ArrayStoreException
• ClassCastException
• IllegalArgumentException
• IllegalThreadStateException
• NullPointerException
• NumberFormatException
• SecurityException
• StringIndexOutOfBoundsException

❖ Two types of exceptions:


1) Checked exceptions
2) Unchecked exceptions

1) Checked exceptions
• All exceptions other than Runtime Exceptions are known as checked exceptions.
• Compiler checks them during compilation
• If these exceptions are not handled/ declared in the program, it will give compilation
error.
• Examples of Checked Exceptions :-
– ClassNotFoundException
– IllegalAccessException
– NoSuchFieldException
– EOFException etc.

2) Unchecked exceptions
• Runtime Exceptions are known as unchecked exceptions.
• the compiler do not check whether the exceptions are handled/declared in the program
• But it is the duty of the programmer to handle these exceptions and provide a safe exit.
• Examples of Unchecked Exceptions :-
– ArithmeticException

2
333
Java Programming (314317) Chapter-3
– ArrayIndexOutOfBoundsException
– NullPointerException
– NegativeArraySizeException etc.

Exception Handling in Java


• When an exception occurs, program terminates abnormally.
• For continuing the program execution, the user should try to catch the exception object thrown
by the error condition and then display an appropriate message for taking corrective actions.
• This task is known as Exception handling
• This mechanism consists of :
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 actions (Handle the Exception)
• Java handles exceptions with 5 keywords:
1) try 2) catch 3) finally 4) Throw 5) throws
• The basic concept of exception handling are throwing an exception and catching it.

1) try block
• The code which might raise exception must be enclosed within try-block
• try-block must be followed by either catch-block or finally-block, at the end.
• ode inside try-block must always be wrapped inside curly braces
• Three forms
1. try-catch block
2. try-finally block
3. try-catch-finally blocks
• Syntax:
try
{
//statements that may cause an exception
}

3
333
Java Programming (314317) Chapter-3
2) catch block
• Contains handling code for any exception raised from corresponding try-block and it must
be enclosed within catch block
• code inside catch-block must always be wrapped inside curly braces
• Syntax:
catch (TypeException object)
{
//error handling code
}
3) finally block
• A finally statement must be associated with a try statement.
• finally block is executed regardless of whether respective exception is handled or not
• used to perform clean-up activities or code clean-up
• Two forms
– try-finally
– try-catch-finally
• Syntax:
finally
{
// block of code to be executed before try block ends
}
4) throw clause
• to throw/raise exception explicitly at runtime
• throw keyword is used to throw user-defined exception or custom exception
• We can throw either checked or unchecked exception.
• Syntax
throw new ThrowableInstance();
• Example:
throw new ArithmeticException("/ by zero");

5) throws clause
• The throws keyword is used to declare an exceptionalong with the method definition.
• Any number of exceptions can be specified using throws clause, but they are all need to be
separated by commas.
• It is mainly used for checked exception
• Used to indicate that this method might throw one of the listed type exceptions.
• The caller of these methods has to handle the exception using a try-catch block.
• Syntax:
void method_name() throws TypeException1, TypeException2,…, TypeExceptionN
{
// body of the method
}

4
333
Java Programming (314317) Chapter-3

➢ Program for Exception Handling


class ExceptionHandling
{
public static void main(String args[])
{
try
{
int c=40/0;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by Zero");
}
}
}

try-catch block:
try
{
//statements that may cause an exception
}
catch (TypeException object)
{
//error handling code
}

➢ Program on try-catch block


class TryCatch
{
public static void main(String args[])
{
try
{
int c=40/0;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by Zero");
}
}
}

5
333
Java Programming (314317) Chapter-3

multi-catch block:
try
{
//statements that may cause an exception
}
catch (TypeException1 object)
{
//error handling code
}
catch (TypeException2 object)
{
//error handling code
}
……

➢ Program on multi-catch block


class MultiCatch
{
public static void main(String args[])
{
try
{
int a[]=new int[7];
a[4]=30/0;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“wrong array index");
}
}
}

Nested try-catch block:


• One try-catch block can be present in another try’s body. This is called Nesting of try
catch blocks.
• Whenever a inner-try block does not have a catch block for a particular exception, then the
catch blocks of parent try block are inspected for that exception.
• If no catch block matches, then the java run-time system will handle the exception
6
333
Java Programming (314317) Chapter-3

• Syntax of Nested try Catch


try
{
statement 1;
try
{
statement 2;
}
catch(Exception e1)
{
//Exception Message
}
}
catch(Exception e2) //Catch of parent try block
{ //Exception Message
}

➢ Program on nested try-catch block


class NestedTry
{
public static void main(String args[])
{
try
{
int a[] = { 1, 2, 3, 4, 5 };
System.out.println(a[5]);

try
{
int x = a[2] / 0;
}
catch (ArithmeticException e2)
{
System.out.println("division by zero ");
}
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("Invalid array index");
}
}
}

7
333
Java Programming (314317) Chapter-3

➢ Program on finally block


class FinallyDemo
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

➢ Program on throws clause


class ThrowsDemo
{
void div() throws ArithmeticException
{
int data=25/0;
System.out.println(data);
}
public static void main(String args[])
{
ThrowsDemo td=new ThrowsDemo();
try
{
td.div();
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}

8
333
Java Programming (314317) Chapter-3
}
}

Difference between throw & throws:

Sr.
throw keyword throws keyword
No.
throw is used to explicitly throw an
1 throws is used to declare an exception.
exception.
checked exception can not be propagated checked exception can be propagated with
2
without throw. throws.
3 throw is followed by an instance. throws is followed by class.

4 throw is used within the method. throws is used with the method signature.
You can declare multiple exception e.g.
5 You cannot throw multiple exception public void method()throws
IOException,SQLException.

User Defined Exceptions/ Own Exceptions / Custom Exception


• If we want to create our own exception types then just define a subclass of Exception.
• User defined exceptions are thrown using ‘throw’ keyword.
• Constructor of Exception class
1. Exception( )
2. Exception(String msg)
• The first form creates an exception that has no description. The second form specifies a
description of the exception.

➢ Program on throw clause or user defined exception


Write a program to input name and age of a person and throws an user define exception
if entered age is negative.

import java.util.*;
class NegativeException extends Exception
{
NegativeException(String msg)
{
super(msg);
}
}

9
333
Java Programming (314317) Chapter-3
class NegativeDemo
{
public static void main(String args[])
{
int age=0;
String name;
Scanner sc=new Scanner(System.in));

System.out.println("enter age of person");


age=sc.nextInt();
System.out.println("enter name of person");
name=sc.next();

try
{
if(age<0)
throw new NegativeException("Age is negative");
else
System.out.println("age is positive");
}
catch(NegativeException e)
{
System.out.println(e);
}
}
}

4.2Multithreading
• A multithreaded program contains two or more parts that can run concurrently. Multithreading
is a specialized form of multitasking
• Each part of such a program is called a thread. A thread is a single sequential flow of control
within a program. Each thread defines a separate path of execution.
• Threads are lightweight processes. They share the process’s resource, including memory and
are more efficient.
• JVM allows an application to have multiple threads of execution running concurrently.
• Thread has a priority. Threads with higher priority are executed in preference to threads with
lower priority. Overhead of switching between threads is less.
• Advantages:
1. Reduces the computation time.
2. Improves performance of an application.
3. Threads distribute the same address space so it saves the memory.
4. Context switching between threads is usually less costly than between processes.

10
333
Java Programming (314317) Chapter-3
5. Cost of communication between threads is comparatively low.

Fig1: A multithreaded program


• Threads may switch or exchange data/results

Creation of Thread
Two ways
1. Create a class that extends the Thread class
2. Create a class that implements the Runnable interface

The run () method makes up entire body of thread and is the only method in which the threads
behaviour can be implemented.

1) Extending Thread class


The Thread class can be extended as follows
1. Declare the class extending the Thread class.
2. Implements the run() method
The extending class must override the run() method, which is the entry point of new
thread.

class MyThread extends Thread


{
public void run()
{
// thread body of execution
}
}
3. Create a thread object:
MyThread th1 = new MyThread();
4. Start Execution of threads:
th1.start();

11
333
Java Programming (314317) Chapter-3

➢ Program on extending Thread class


class MyThread extends Thread
{
public void run()
{
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1
{
public static void main(String [] args )
{
MyThread t = new MyThread();
t.start();
}
}

2) Implementing Runnable Interface


1. Declare the class implementing Runnable interface.
2. Implements the run() method
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
3. Create thread object that instantiated from this “runnable” class.
MyThread mt = new MyThread();
Thread th=new Thread(mt);
4. Start Execution of threads:
th.start();

➢ Program on implementing Runnable interface


class MyThread implements Runnable
{
public void run()
{
System.out.println(" this thread is running ... ");
}
}

12
333
Java Programming (314317) Chapter-3
class ThreadEx1
{
public static void main(String [] args )
{
MyThread mt = new MyThread();
Thread th = new Thread(mt);
th.start();
}
}

Life Cycle of Thread

Fig2: Life Cycle of Thread

Thread has five different states throughout its life.


1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Thread should be in any one state of above and it can be move from one state to another by different
methods.

13
333
Java Programming (314317) Chapter-3
1) New Born State
• When a thread object is created it is said to be in a new born state.
• It can be scheduled for running by start() or killed by stop().
• If start( ) method is called then the thread goes to ready to run mode.
• If the stop( ) method is called then the thread goes to dead state.

2) Runnable State:
• It means that thread is ready for execution and is waiting for the availability of the processor
i.e. the threads has joined the queue and is waiting for execution.
• If all threads have equal priority then they are given time slots for execution in round robin
fashion.
• The thread that relinquishes control joins the queue at the end and again waits for its turn. A
thread can relinquish the control to another before its turn comes by yield().

3) Running State:
• It means that the processor has given its time to the thread for execution.
• The thread runs until it relinquishes (give up) control on its own or it is pre-empted by a higher
priority thread.
• The thread can finish its work and end normally.
• The thread can also be forced to give up the control when one of the following conditions arise
1. A thread can be suspended by suspend ( ) method. It is resumed by using the resume ()
method.
2. A thread can be made to sleep for a particular time by using the sleep (milliseconds)
method.
It is wake up after time elapses.
3. A thread can be made to wait until a particular event occur using the wait() method. It is
wake up by notify ( ) method.

4) Blocked state:
• A thread can be temporarily suspended or blocked from entering into the runnable and running
state by using either of the following thread method
1. suspend()
2. wait()
3. sleep()
• Suspended thread is resumed by using the resume() method.
• Sleeping thread wakes up after time elapses/ over
• Waited thread wakes up by notify( ) method.

5) Dead State:
• Whenever we want to stop a thread form running further we can call its stop().
• The running thread ends its life when it has completed executing the run() method which is
called natural dead.
• The thread can also be killed at any stage by using the stop( ) method.

14
333
Java Programming (314317) Chapter-3

Creating Multiple Threads


➢ Program on multiple threads

Write a program to create two threads, one to print numbers in original order and other
to reverse order from 1 to 50.

class Original extends Thread


{
public void run()
{
for(int i=1;i<=50;i++)
{
System.out.println(“Original i=”+i);
}
}
}
class Reverse extends Thread
{
public void run()
{
for(int i=50;i>=1;i--)
{
System.out.println(“Reverse i=”+i);
}
}
}
class ThreadDemo
{
public static void main(String [] args )
{
Original ot=new Original();
Reverse rt=new Reverse();

ot.start();
rt.start();
}
}

Thread Methods:
1) start()
– Creates a new thread and makes it runnable
– This method can be called only once.
15
333
Java Programming (314317) Chapter-3
– Syntax:
public void start()
{
}
– Ex: threadobj.start()
2) run()
– Task to be executed by thread is defined in run() method.
– Syntax:
public void run()
{
//thread task here
}
3) stop()
– Whenever we want to stop a thread from running further, call stop() method.
– Syntax:
public void stop()
{
}
– Ex: threadobj.stop()
– This method causes the thread to move to dead state.
– The stop may used when the premature death of thread is desired.
4) suspend()
– This method puts a thread in suspended state and can be resumed using resume() method.
– Syntax :
public void suspend()
{
}
5) resume()
– This method resumes a thread which was suspended using suspend() method.
– Syntax :
public void resume()
{
}
6) yield()
– The yield() method causes the currently executing thread object to temporarily pause and
allow other threads to execute
– Syntax :
public static void yield()
{
}

16
333
Java Programming (314317) Chapter-3
7) wait()
– This method causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.
– syntax :
public final void wait()
{
}
8) sleep()
• Syntax:
public void sleep(int m) throws InterruptedException
public void sleep(int m, int n) throws InterruptedException
– The thread sleeps for m milliseconds, plus n nanoseconds.

Thread Exceptions
• Mostly call to sleep() method is enclosed within a try block and followed by catch block. This
is because the sleep() method threads an exception, which must be caught. If exception thread
is not catched, program, will not compile.
• Java run system will throw IllegelThreadStateException whenever attempt is made to invoke a
method that a thread cannot handle in given state.
• For example, a sleeping thread cannot deal with the resume() method because a sleeping thread
cannot receive any instructions.
• When thread method is called which is throwing an exception the appropriate exception
handler must be supplied which catch exception thrown by thread.
• The catch statement can take any one of the following four forms
1. catch(ThreadDeath e)
{
- ------- //Killed thread
}
2. catch(InterruptedException e)
{
- ------- //cannot handle it in current state
}
3. catch(IllegalArgumentException e)
{
- --------- //Illegal method argument
}
4. catch(Exception e)
{
- -------- // any other
}

17
333
Java Programming (314317) Chapter-3

Thread priority & methods


• A java program requires at least one thread called as main thread. The main thread is actually
the main method module which is designed to create and start other threads.
• In java each thread is assigned a priority which affects the order in which it is scheduled for
running. Thread priority is used to decide when to switch from one running thread to another.
Threads of same priority are given equal treatment by the java scheduler.
• When a thread is created, it inherits the priority of the thread that created it.
• Thread priorities can take value from 1-10.
• Thread class defines default priority constant values as
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (Default Priority)
MAX_PRIORITY = 10
• The main thread is created with priority NORM_PRIORITY.

➢ Thread PriorityMethods:
1. setPriority:
– This method is used to assign new priority to the thread.
– Syntax:
public void setPriority(int number)
– Example:
threadobj.setPriority(Thread.MIN_PRIORITY);

2. getPriority:
– It obtain the priority of the thread and returns integer value.
– Syntax:
public intgetPriority();
– Example:
int prority=threadobj.getPriority();

➢ Program on Thread Priority

class One extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(“One i=”+i);
}
}
}
18
333
Java Programming (314317) Chapter-3
class Two extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(“Two i=”+i);
}
}
}
class PriorityDemo
{
public static void main(String [] args )
{
One ot=new One();
Two tt=new Two();

ot.setPriority(Thread.MIN_PRIORITY);
tt.setPriority(Thread.MAX_PRIORITY);

ot.start();
tt.start();
}
}

Inter thread communication


• When a two or more thread exits in an application and they are communicating each other by
exchanging information, then it is called as inter thread communication.
• Following are three methods which makes thread communication possible:
wait(), notify() and notifyAll().
• All these methods belong to object class as final so that all classes have them. They must be
used within a synchronized block only.
1. wait()-
It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
public final void wait(long timeout)
public final void wait()
2. notify()-
It wakes up one single thread that called wait() on the same object. It should be noted
that calling notify() does not actually give up a lock on a resource.
public final void notify()

19
333
Java Programming (314317) Chapter-3
3. notifyAll()-
It wakes up all the threads that called wait() on the same object.
public final void notifyAll()

Synchronization
• When two or more threads wants to access to a shared resources, there is requirement of the
shared resource must be used by only one thread at a time.
• The synchronized keyword is used to achieve this.
• Synchronized code will only be executed by one thread at a time.
• When we declare a method synchronized, Java creates a “monitor or lock” and hands it to the
thread that calls the method first time.
• As long as the method holds the monitor, no other thread can enter the synchronized section of
code.
• Two ways:
1. Synchronized mehod
synchronized returntype methodname(paralist)
{

2. Synchronized block
synchronized(sync_object)
{

➢ Program on Synchronized Method

class Shared
{
synchronized void display(String msg)
{
System.out.print("["+msg);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);

20
333
Java Programming (314317) Chapter-3
}
System.out.println("]");
}
}
class MyThread extends Thread
{
Shared sh;
String msg;
MyThread(String ms,Shared s)
{
msg=ms;
sh=s;
}
public void run()
{
sh.display(msg);
}
}
class SyncMethod
{
public static void main(String args[])
{
Shared sh=new Shared();
MyThread th1=new MyThread("Hi",sh);
MyThread th2=new MyThread("Hello",sh);
MyThread th3=new MyThread("Thanks",sh);
th1.start();
th2.start();
th3.start();
}
}

➢ Program on Synchronized Block

class Shared
{
void display(String msg)
{
System.out.print("["+msg);
try
{
Thread.sleep(500);
}
21
333
Java Programming (314317) Chapter-3
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("]");
}
}
class MyThread extends Thread
{
Shared sh;
String msg;
MyThread(String ms,Shared s)
{
msg=ms;
sh=s;
}
public void run()
{
synchronized(sh)
{
sh.display(msg);
}
}
}
class SyncBlock
{
public static void main(String args[])
{
Shared sh=new Shared();
MyThread th1=new MyThread("Hi",sh);
MyThread th2=new MyThread("Hello",sh);
MyThread th3=new MyThread("Thanks",sh);
th1.start();
th2.start();
th3.start();
}
}

Deadlock
• Deadlock in java is a part of multithreading
• When a thread is waiting for an object lock, that is acquired by another thread and second
thread is waiting for an object lock that is acquired by first thread.

22
333
Java Programming (314317) Chapter-3

• Since, both threads are waiting for each other to release the lock, the condition is called
deadlock.

Fig3: Deadlock
• Thread1 locks/holds ResourceA and it is waiting for ResourceB which is locked/held by
Thread2. Similarly, Thread2 locks/holds ResourceB and it is waiting for ResourceA which
is locked/held by Thread1. That is both the threads are waiting for each other to release the
resources. But no one is releasing. Hence, system functioning is stopped & this situation is
known as Deadlock.
• For Example:
Thread A
synchronized resource1
{
synchronized resource2
{

}
}
Thread B
synchronized resource2
{
synchronized resource1
{

}
}

23
333
Java Programming (314317) Chapter-3

Questions on Chapter 4:

1) Explain the following clause w.r.t. exception handling : (i) try (ii) catch (iii) throw (iv) finally
2) Describe types of Errors and Exceptions in details.
3) What is an exception ? How it is handled ? Give suitable example.
4) Write a program to accept password from user and throw “Authentication failure” exception if
password is incorrect.
5) Write program. Define an exception called ‘No match Exception’ that is thrown when a string
is not equal to MSBTE”.
6) What is thread priority ? Write default priority values and methods to
7) change them.
8) What is synchronization ? When do we use it ? Explain synchronization of two threads
9) Describe following methods of thread :
(i)suspend ( ) (ii) resume ( ) (iii) sleep ( ) (iv) notify ( ) (v) stop () (vi) wait ( )
10) Write a thread program for implementing the ‘Runnable interface’.
11) Explain life cycle of thread with a neat diagram.
12) What is thread ? Draw thread life cycle diagram in Java.
13) Write a program to create two threads, one to print numbers in even no and odd no from 1 to
50.
14) Write a program to create two threads so one thread will print 1 to 10 numbers whereas other
will print 11 to 20 numbers.
15) Write a program to define two threads for displaying even and odd numbers respectively with a
delay of 500 ms after each number.

24

You might also like