0% found this document useful (0 votes)
9 views57 pages

Multi Threading and Exception Handling UPLOAD

Uploaded by

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

Multi Threading and Exception Handling UPLOAD

Uploaded by

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

4.

0 MULTI THREADING AND EXCEPTION HANDLING

4.1 Understand concept of Threading


4.1.1 Define thread and its uses in Java programming
4.1.2 Explain the different types of thread.
a. Single thread
b. Multiple thread
4.1.3 Differentiate between multi-tasking and multi-threading
4.1.4 List the methods involved in life cycle of a thread
4.1.5 Write multithreaded application
4.0 MULTI-THREADING
4.1 MULTI-THREADING
4.1 Basics of Threading
4.1.1 Describe the use of Thread in Java programme.
4.1.2 Explain the different types of Thread:
a) Single thread
b) Multiple thread
4.1.3 Differentiate between multi-tasking and multi-
threading.
4.1.4 Create multi-threaded application.
4.1.5 List the methods involved in life cycle of a
thread.
• © Jabatan Teknologi Maklumat & Komunikasi
3
• Politeknik Sultan Idris Shah
4.1.1 Describe the use of Thread in Java programme.

• A program can be split into separate tasks and


further into threads. This increases the effective
usage of CPU during execution.
• The popularity of threading increased with Graphical
User Interfaces. Threading system allowed the user
to attain better performance in a program.
• The introduction of threads created an illusion that
the program's performance was faster.

4
4.1.2 Explain the different types of Thread
Definition
Thread can be defined as single, sequential flow of
control within a program.

Two types
• Single thread
• Multiple threads

5
4.1.2 Explain the different types of Thread

Single threaded Application

 A task or process that is made up of only one thread


is single-thread.
 A program that supports single thread is called
single threaded application.

6
4.1.2 Explain the different types of Thread
Multi threaded Application

 A task or process that is made of more than one


thread is multiple threading.
 A program that supports more than one thread is
multi-threaded application

7
4.1.3 Differentiate between multi-tasking and
multi-threading.

Multi tasking Is the ability of an operating system to execute


more than one program simultaneously.

8
Difference Between Multitasking and Multithreading
S.No: Multitasking Multithreading

1. More than one program gets More than one part of a program
executed simultaneously. called threads is executed
simultaneously.

2. Multitasking is a timesharing Multithreading is also a timesharing


process. CPU switches from process. CPU switches from one
one program to another program activity to another activity within the
so quickly to complete all the program so quickly to complete all the
programs simultaneously. activities simultaneously.

3. Since each program occupies Multithreading is a light weight process


different memory location, because the activities/ threads share
Multitasking is called as the same memory space.
heavyweight process

9
4.1.4 Create multi-threaded application

A process that is made of only one thread is called single


threaded application.
class Thread_1{
public static void main(String args[]){
………
………
}
}
10
Example:
class Thread_1{
public static void main(String agrs[]){
System.out.println("Single Threaded");
}
}

• © Jabatan Teknologi Maklumat & Komunikasi


11
• Politeknik Sultan Idris Shah
In a single threaded application, main() itself acts as a thread.
If a program requires more than one thread, it needs to be
created
………………..
………………..
………………..

Main Thread

……………….. Switching ………………..


……………….. ………………..
……………….. ………………..

Thread 1 Thread 2

12
Declaring a Thread Class - Example
class Thread_2 extends Thread
{
……………..
……………..
……………..
……………..
……………..
}
13
Declaring a Thread class – Syntax
class <new thread> extends Thread
{
……………..
……………..
……………..
……………..
……………..
}

14
Starting a new Thread - Syntax
Threadname objectname = new Threadname;
objectname.start();

Starting new Thread - Example


Thread_2 obj = new Thread_2();
obj.start();
//Program to create a multithreaded application
class Thread_2 extends Thread{
public void run(){
System.out.println("Thread in running state");
}}
class ThreadDemo{
public static void main(String args[]){
Thread_2 obj = new Thread_2();
obj.start();
System.out.println("Thread in runnable state");
}}

• © Jabatan Teknologi Maklumat & Komunikasi


16
• Politeknik Sultan Idris Shah
A thread during the running state can be moved to the not
runnable state. This can be achieved by:
• Stopping a thread
• Blocking a thread

Syntax - objectname.stop();
Example - obj.stop();

• © Jabatan Teknologi Maklumat & Komunikasi


17
• Politeknik Sultan Idris Shah
A thread can be temporarily suspended or blocked from running.
The thread is blocked from entering the runnable or running
state. A thread can be blocked using any of the three
methods.
sleep() - The thread is blocked for a specified time. The thread
returns to the runnable state when the specified time is
elapsed.
suspend() - The thread is suspended until further ordered. The
resume() method is called.
wait() - The thread is blocked until a condition occurs. The
notify() method is called.

18
Methods in Thread Class
Methods Description

start() Used to initiate the thread.

stop() Used to kill the thread.

run() Used to implement the body of the


thread and its behaviour.

yield() Used to give the control to another


thread of equal priority.

suspend() Used to suspend the thread.

resume() Used to resume the suspended


thread.

19
sleep(t) Used to specify the time frame
for suspension.

wait() Used to make the thread wait


until some event occurs.

notify() Used to schedule the thread to


run again.

20
Life Cycle of a Thread

New Thread Runnable Not runnable

Dead run() method terminates

21
States of Threads
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state.

22
States Description

Newborn When a thread is created.

Runnable It is ready for execution and is


waiting for the availability of
CPU.
Running It is the time given for the
execution of the thread.

Blocked The thread is suspended,


sleeping or waiting to fulfill
certain requirements.
Dead A thread completes executing
the run() method, ends its life.

23
4.0 MULTI THREADING AND EXCEPTION HANDLING

4.2 Understand concept of exception


handling
4.2.1 Define the concept of exception handling
mechanism.
4.2.2 Explain the use of exception handling.
4.2.3 Explain the different types of exceptions in
RuntimeException
a. NumberFormatException
b. ArrayIndexOutOfBoundsException
c. ArithmeticException
d. ArrayStoreException
e. ClassCastException
4.2.4 Create Java program using exception handling.
4.2.1 Define the concept of exception handling
mechanism.
What Is an Exception? .
The term exception is shorthand for the phrase "exceptional
event.“
Definition:
An exception is an event, which occurs during the
execution of a program, that disrupts the normal flow of
the program's instructions

26
 When an error occurs within a method, the method creates an
object and hands it off to the runtime system.
 The object, called an exception object, contains information
about the error, including its type and the state of the program
when the error occurred.
 Creating an exception object and handing it to the runtime
system is called throwing an exception.
 After a method throws an exception, the runtime system
attempts to find something to handle it.
 The set of possible "somethings" to handle the exception is the
ordered list of methods that had been called to get to the method
where the error occurred.
 The list of methods is known as the call stack 27
The call stack.

28
 The runtime system searches the call stack for a method
that contains a block of code that can handle the exception.
 This block of code is called an exception handler.
 The search begins with the method in which the error
occurred and proceeds through the call stack in the reverse
order in which the methods were called.
 When an appropriate handler is found, the runtime system
passes the exception to the handler.
 An exception handler is considered appropriate if the type
of the exception object thrown matches the type that can
be handled by the handler.
29
 The exception handler chosen is said to catch the exception.
 If the runtime system exhaustively searches all the methods on the
call stack without finding an appropriate exception handler, as shown
in the next figure, the runtime system (and, consequently, the
program) terminates.

30
An exception is a problem that arises during the execution of a program.
An exception can occur for many different reasons, including the
following:
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of
communications, or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by


programmer error, and others by physical resources that have failed in
some manner.

31
Three categories of exceptions:

1. Checked exceptions:
A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the
programmer.
For example, if a file is to be opened, but the file cannot
be found, an exception occurs.
These exceptions cannot simply be ignored at the time of
compilation.

32
2. Runtime exceptions:
A runtime exception is an exception that occurs that
probably could have been avoided by the programmer.
As opposed to checked exceptions, runtime exceptions
are ignored at the time of compilation.

33
3. Errors:
These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer.
Errors are typically ignored in your code because you can
rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.

34
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than
the exception class there is another subclass called Error which is
derived from the Throwable class.

35
4.2.2 Explain the use of exception handling

A method catches an exception using a combination of the try and catch


keywords. A try/catch block is placed around the code that might
generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the
following
Syntax
try {
//Protected code
}catch(Exceptiontype object) {
//Catch block
}
36
Exception Handling Mechanism

37
Example:
class Excep1{
public static void main(String args[]){
int A,B,C=0;
A=Integer.parseInt(args[0]);
B=Integer.parseInt(args[1]);
try {
C= A/B; // B have value of 0,exception will occur
}
catch(ArithmeticException ae){
System.out.println("Caught Exception :- " + ae.getMessage());
}
System.out.println("The Value of C:- " + C);
} ictl}
38
Output:
C:\Program Files\Java\jdk1.6.0_27\bin>java Excep1 0 2
The Value of C:- 0

C:\Program Files\Java\jdk1.6.0_27\bin>java Excep1 2 0


Caught Exception :- / by zero
The Value of C:- 0

39
• The above example, declares 3 variables A, B and C in line 6.
• If the user enters the value 0 for B, the statement C = A/B in line 11
generates an Arithmetic Exception.
• So this statement is put inside the try block. If you have a try block
then you should have catch block to handle the Exception.
• In the catch block, an object ae is created for the ArithmeticException
type in line 13.
• The catch block catches the Arithmetic Exception. The object ae holds
the reference of the exception.
• Using the getMessage() method the content of the exception is
displayed in line 15. if try and catch blocks are not used then the
program terminates abruptly.

40
Multiple catch Blocks:
• A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following:

try {
//Protected code
}catch(ExceptionType1 e1) {
//Catch block }catch(ExceptionType2 e2) {
//Catch block }catch(ExceptionType3 e3) {
//Catch block }

41
42
The above example contains two catch statements. The statement c=a/b
in line 10 will generate Arithmetic Exception and int var = arr[2]-arr[1] in
line 11 will generate ArrayIndexOutOfBound Exception.
The Arithmetic Exception is raised first and hence the control
automatically jumps to corresponding catch statement. The statement
System.out.println("Arithmetic Exception") is executed and the the
ArithmeticException is printed on the monitor.

43
A sample program to illustrate the use of Exception class to catch any
type of exception generated by the program
class ExcepClassDemo{
public static void main(String args[]){
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c;
int arr[]={10,20};
try{
c=b/a;
int arr[2] = arr[1]-arr[0];
}catch (Exception e){
System.out.println("Exception Generated");
}}}
44
Till now you have written programs to catch exceptions thrown by
Java run-time system. The throw statement allows you to throw
exceptions that are not thrown by Java run-time system . When
throw is used inside the program, it implies that the program is going
to throw an exception.

Syntax
throw new exceptiontype ();

45
class ThrowDemo{
public static void main(String args[]) {
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
try {
float z = (float)x/(float)y;
if(z<0.01)
throw new Exception("Number is too small");
} catch(Exception e) {
System.out.println("Caught the exception:- " +
e.getMessage());
}
System.out.println("The value of z:- Output:
" + z);
}} C:\java>java ThrowDemo 1 100
Caught the exception:- Number is too small
The value of z:- 0.01
The finally block
• If you define a finally block it will surely execute, regardless of whether the
exception is thrown or not.
• The finally block contains statements for doing the final process such as
deallocation of memory etc.
• It may be added immediately after the try block or after the last catch block.
• A try block should have at least one catch block or finally block immediately
following it.
Syntax: finally{
statements ;// code to be executed
}
Example: finally{
System.out.println("These statements will be executed regardless of
whether an exception is thrown or not");
}
Example:
class FinallyDemo{
public static void main(String args[]){
int a=0,b=5,c=0; Output:
C:\java>javac FinallyDemo.java
try{ C:\java>java FinallyDemo
c=b/a; I will execute if the exception is generated
I always execute at last
}catch(ArithmeticException e){
System.out.println("I will execute if the exception is
generated");
}finally {
System.out.println("I always execute at last");
} } }
Creating User-Defined Exceptions
• The built-in exceptions in Java handle most of the common errors. In
some situations you need to handle exceptions that are specific to
your applications.
• Consider that you are developing an application in Java for a
company.
• The code may raise an exception in certain situation. The exception,
which is raised, is only specific for that application.
• If this exception generated is not defined in the built-in exceptions of
Java, then you need to create a user-defined exception, which can
handle the situation
• When you want to create user-defined exception, it should be the sub
class of class Throwable.
• The class Exception is the subclass for the class Throwable. Therefore
all the user-defined exceptions are subclasses of the class Throwable
Example: try{
import java.lang.Exception; float c=(float)a/(float)b;
class MyException extends if(c>0.01)
Exception{ {
MyException(String message){ throw new MyException("The
System.out.println(message); Number is greater than 0.01");
} }
} }
class UserExcep{ catch(MyException myexcep)
public static void main(String {
args[]){ System.out.println("Caught
int a=2,b=100; my exception");
Continue }}}
4.2.3 Explain the different types of exceptions in
RuntimeException
a. NumberFormatException
public class NumberFormatException extends
IllegalArgumentException

Thrown to indicate that the application has attempted to convert a


string to one of the numeric types, but that the string does not have
the appropriate format.

NumberFormatException()
Constructs a NumberFormatException with no detail message

NumberFormatException(String s)
Constructs a NumberFormatException with the specified detail
message.
4.2.3 Explain the different types of exceptions in
RuntimeException
b. ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBoundsException extends
IndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index.
The index is either negative or greater than or equal to the size of the
array
4.2.3 Explain the different types of exceptions in
RuntimeException
c. ArithmeticException
public class ArithmeticException extends RuntimeException

Thrown when an exceptional arithmetic condition has occurred.


For example, an integer "divide by zero" throws an instance of this class.
ArithmeticException objects may be constructed by the virtual
machine as if suppression were disabled and/or the stack trace
was not writable.
4.2.3 Explain the different types of exceptions in
RuntimeException
d. ArrayStoreException
public class ArrayStoreException extends RuntimeException

Thrown to indicate that an attempt has been made to store the wrong
type of object into an array of objects. For example, the following code
generates an ArrayStoreException:
Object x[] = new String[3];
x[0] = new Integer(0);
4.2.3 Explain the different types of exceptions in
RuntimeException
blic
e. ClassCastException
Thrown
classtoClassCastException
indicate that the code has attempted
extends to cast an object to a
RuntimeException
subclass of which it is not an instance.

For example, the following code generates a ClassCastException:


Object x = new Integer(0);
System.out.println((String)x);
PREPARE FOR YOUR FINAL EXAM
&
GOOD LUCK

You might also like