Ch4 JPR

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 72

Exception Handling &

Multithreading
Marks-12
4.1 Errors & Exception
• Types of Error
two categories:-
1. Compile time errors
2. Runtime errors
• 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.
4.1 Errors & Exception
• 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
4.1 Errors & Exception
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.
4.1 Errors & Exception
• 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).
4.1 Errors & Exception
• 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
Types of exceptions
• Two types of exceptions:
1) Checked exceptions
2) Unchecked exceptions
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.
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
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.
Some Exception Classes
• ArithmeticException
• ArrayIndexOutOfBoundsException
• ArrayStoreException
• ClassCastException
• IllegalArgumentException
• IllegalThreadStateException
• NullPointerException
• NumberFormatException
• SecurityException
• StringIndexOutOfBoundsException
An object of
exception class exception
int data=10/0; is thrown object

No Is Yes
handled
?

JVM
1)Prints out exception Rest of the code is
description executed
2) Prints the stack trace
3) Terminate the program
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
• 5 important keywords related to Java exception
handling
– try
– catch
– finally
– throw
Exception Handling in Java
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)
Syntax of Exception Handling Code
• The basic concept of exception handling are throwing an
exception and catching it.
try & catch try Block

Statement that
causes Exception

Catch Block

Statement that
handles the Exception
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
– try-catch block
– Try-finally block
– try-catch-finally blocks
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
try-catch Block

try
{
//statements that may cause an exception
}
catch (ExceptionType object)
{
//error handling code
}
Class TryCatch
{
public static void main(String args[])
{
try
{
int c=40/0;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by Zero");
}
}
}
Multiple catch
try
{
//statements that may cause an exception
}
catch(ExceptionType1 e1)
{
//error handling code1
}
catch(ExceptionType2 e2)
{
//error handling code2
}
……
Sequence of Events
Preceding step

try block

statement

unmatched catch

matching catch

unmatched catch

next step
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
• One try-catch block can be present in the 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.
• 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
}
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("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exists");
}
}
}
What is 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

try try
{ {
……. ……
} }
finally catch(…)
{ { ……..
……… }
} Finally
{
}
Program Code

no Exception Yes
Occurred ?

no Yes
Exception
Handled ?

Finally block is executed


Sequence for finally clause

Preceding step
try block

statement

unmatched catch
matching catch
unmatched catch
finally
next step
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...");
}
}
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 of throw statement
throw new AnyThrowableInstance();
• Example:
throw new ArithmeticException("/ by
zero");
class TestThrow
{
void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
TestThrow tt=new TestThrow();
tt.validate(13);
System.out.println("rest of the code...");
}
}
throws clause
• The throws keyword is used to declare an exception.
• It gives an information to the programmer that there
may occur an exception.
• 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 in the signature of method 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.
throws clause
Syntax of throws keyword:

void method_name() throws ExceptionType1,ExceptionType2,…,


ExceptionTypeN
{
...
}
throw keyword throws keyword
throw is used to explicitly throw an throws is used to declare an
exception. exception.
checked exception can not be checked exception can be propagated
propagated without throw. with throws.
throw is followed by an instance. throws is followed by class.

throw is used within the method. throws is used with the method
signature.
You cannot throw multiple You can declare multiple exception
exception e.g.
public void method()throws
IOException,SQLException.
User Defined Exception
• User Defined Exception or custom exception
• Way to create own exception class and
throws that exception using ‘throw’ keyword.
This can be done by extending the class
Exception.
class NegativeAgeException extends Exception
{
public NegativeAgeException (String msg)
{
super(msg);
}
}
class UseEx
{
public static void main(String[] args)
{
int age=-2;
try
{
if(age < 0)
throw new NegativeAeException("Age
can't be negative");
else
System.out.orintln(“Age=“+age)

}
catch (NegativeAgeException e)
{
System.out.orintln(e);
}
}
}

Que: Write a program to accept password from user and throw “Authentication
failure” exception if password is incorrect.
Multitasking
• Executing several tasks simultaneously
• Two types:
1. Process based multitasking
2. Thread based multitasking
• Process based multitasking
• Executing several tasks simultaneously where each
task is separate independent process
• It is best suitable at OS level
• Ex: While writing a program in editor, we are
listening music and downloading a file from internet
Multitasking
• Thread based multitasking
• Executing several tasks simultaneously where each
task is separate independent part of the same
process/program
• It is best suitable at programming level
Multithreading
• A multithreaded program contains two or more parts
that can run concurrently.
• Each part of such a program is called a thread
• each thread defines a separate path of execution.
• multithreading is a specialized form of multitasking.
• Threads are lightweight processes
• overhead of switching between threads is less
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Advantages of multithreading
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.
5. Cost of communication between threads is
comparatively low.
A Multithreaded Program

Main Thread

start
start start

Thread A Thread B Thread C

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

In both cases the run() method should be implemented

44
1st method: Extending Thread class
1. Declare the class extending the Thread class.
2. Implements the run() method
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();
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();
}
}
2nd method:
Threads by implementing Runnable interface
1. Declare the class as it is implementing Runnable interface.
2. Implement run() method
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
3. Create thread by defining an object that instantiated from this “runnable”
class as the target of the thread.
MyThread myObject = new MyThread();
Thread th1 = new Thread( myObject );
4. Call the thread‟s start() method to run the thread.
th1.start();
class MyThread implements Runnable
{
public void run()
{
System.out.println(" this thread is running ... ");
}
}
class ThreadEx2
{
public static void main(String [] args )
{
Thread t = new Thread(new MyThread());
t.start();
}
}
Thread Life Cycle
• Thread Life Cycle :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 and it can
be move from one state to another by
different methods and ways.
New Born State:--
• The thread enters the new born state as soon
as it is created.
• 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.
Runnable State:--
• thread is ready for execution and is waiting for
the availability of the processor i.e. the thread
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.
• A thread can relinquish the control to another
before its turn comes by yield().
• Running State:--
• If the thread is in execution then it is said to be in running
state.
• 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.
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.
– suspend()
– wait()
– sleep()
1. Suspended thread is resumed by using the
resume() method.
2. Sleeping thread wakes up after time elapses
3. Waited thread wakes up by notify( )
method.
Dead State:
• 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.
Thread Methods
void start()
– Creates a new thread and makes it runnable
– This method can be called only once.
aThread.start()
void run()
– The new thread begins its life inside this
method
Thread Methods

Stopping a Thread
• void stop()
– Whenever we want to stop a thread from
running further, call stop() method
aThread.stop()
– This method causes the thread to move to
dead state.
– The stop may used when the premature death
of thread is desired.
Thread Methods
Blocking a Thread
• A thread can also be temporarily suspended or
blocked from entering into the runnable and
running state by using following methods.
– sleep() :blocked for specified time
– suspend() :blocked until further orders ( resume() )
– wait() :blocked until certain conditions occurs
(notify())
• These methods causes the thread to go into
blocked state.
Thread Methods
void yield()
• Causes the currently executing thread object to
temporarily pause and allow other threads to
execute.
• Allow only threads of the same priority to run.
void sleep(int m) or sleep(int m, int n)
– The thread sleeps for m milliseconds,
plus n nanoseconds.
Thread Priority
• Every thread has a priority.
• When a thread is created, it inherits the
priority of the thread that created it.
• The priority values range from 1 to 10, in
increasing priority.
Thread Priority (cont.)
• To set or to change the priority, setPriority()
method is used.
Threadname.setPriority(intNumber);
• The priority of a thread may be obtained using
getPriority()
• Priority constants are defined:
– MIN_PRIORITY=1
– MAX_PRIORITY=10 The main thread is
– NORM_PRIORITY=5 created with priority
NORM_PRIORITY
Synchronization
• When the threads are executed separately to each
other. These threads are called as asynchronous.
• Multi-threaded programs often came to a
situation where one resource access by a lot of
threads and produce unforeseen results.
• So, make sure that only one thread can access a
particular resource at a given point in time with
the help of Java synchronized keyword.
• Synchronized code will only be executed by one
thread at a time.
Synchronization
• 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.
• A monitor is like a key and the thread is that
holds the key can only open the lock.
• Whenever a thread has completed its work it will
handover the monitor the next thread.
Synchronization
• Two ways:
1. Synchronized mehod
synchronized returntype methodname(paralist)
{
--------------
--------------
}

2. Synchronized block
synchronized(sync_object)
{
----------
---------
}
Synchronized Method
class Shared class MyThread extends Thread
{ {
synchronized void display(String msg) Shared sh;
{ String msg;
System.out.print("["+msg); MyThread(String ms,Shared s)
try {
{ msg=ms;
sh=s;
Thread.sleep(500); }
} public void run()
catch(InterruptedException {
e)
sh.display(msg);
{
}
}
System.out.println(e);
}
System.out.println("]");
}
}
Synchronized Method Cont…
class SyncDemo
{
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();
}
}
Synchronized Block
class Shared class MyThread extends Thread
{ {
void display(String msg) Shared sh;
{ String msg;
System.out.print("["+msg); MyThread(String ms,Shared s)
try {
{ msg=ms;
sh=s;
Thread.sleep(500); }
} public void run()
catch(InterruptedException {
e)
synchronized(sh)
{
{
sh.display(msg);
System.out.println(e);
}
}
}
System.out.println("]");
}
}
}
Synchronized Method Cont…
class SyncDemo
{
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.
• Since, both threads are waiting for each other to release
the lock, the condition is called deadlock.
Deadlock
Deadlock
Thread A Thread B
synchronized resource1 synchronized resource2
{ {
synchronized resource2 synchronized resource1
{ {
----- -----
----- -----
} }
} }

You might also like