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

CH 5. Exception Handling & Multithreading

The document discusses exception handling in Java, explaining that exceptions are unwanted events that occur during program execution and Java provides mechanisms like try, catch, throw, throws and finally to handle runtime errors gracefully. It covers different types of exceptions, how to define custom exceptions, and the use of try, catch, multiple catch blocks, finally and throw keywords to implement exception handling in Java programs.

Uploaded by

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

CH 5. Exception Handling & Multithreading

The document discusses exception handling in Java, explaining that exceptions are unwanted events that occur during program execution and Java provides mechanisms like try, catch, throw, throws and finally to handle runtime errors gracefully. It covers different types of exceptions, how to define custom exceptions, and the use of try, catch, multiple catch blocks, finally and throw keywords to implement exception handling in Java programs.

Uploaded by

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

Exception Handling and

Multithreading
Chp 5

By Megha V Gupta
An exception is an unwanted or unexpected
event, which occurs during the execution of a
Exception program.

Handling in The Exception Handling in Java is one of the


powerful mechanism to handle the runtime
Java errors so that normal flow of the application
can be maintained.

Error: An Error indicates serious problem that a


reasonable application should not try to catch.

https://www.youtube.com/wa Exception: Exception indicates conditions that a


tch?v=ohpCMpderow&t=309s reasonable application might try to catch.
Exception Handling in Java
Exception Handling in Java
Exception

• The Exception is the subclass of the Throwable class.


• Exception in java is a Condition or a problem which stops the execution of program.

Exception definition in java :

An exception is a condition that is caused by a Runtime error in a program.

• When the java interpreter caught an error, such as divide by zero, the interpreter creates an exception object
and throws it to inform that an error has occurred.

Exception can be checked Exception or Unchecked exception.

• Checked Exception : Exceptions which are checked by the compiler at run time is called as Checked Exceptions.
• Unchecked Exception : Exceptions which are not checked by the compiler at run time is called as
Unchecked Exceptions.
Exception Handling in Java
Types of error
• Compile time error
• Runtime error

Compile time error


• Java compiler detects all syntax errors and displays it so these errors are
known as compile time error.
• Common compile time errors are missing semi colon, missing bracket.

Run time error


• Run time errors are occurred at Run time after compilation.
• Commonly Occurred Runtime errors
• Divide an integer by zero, converting invalid string to a number.
Steps for Exception Handling
Exception handling mechanism includes a separate error handling code that
performs
• Find the problems (Find exception).
• Inform that an error has occurred (throw exception )
• Receive the error information (catch the exception)
• Take corrective actions (handle the exception)
Try-catch Block
Program Without Try Catch
public class notrycatch
{
public static void main(String[] args)
{
int a=20,b=10,c=10;
int x=a/0;
System.out.println("x="+x);
int y=a/(b+c);
System.out.println("y="+y);
}
}
try and catch statement
✓The scope of a catch clause is restricted to those
statements specified by the immediately preceding try
statement.
✓A catch statement cannot catch an exception thrown by
another try statement.
✓The statements that are protected by the try must be
surrounded by curly braces.
Program With Try Catch
public class trycatch1
{
public static void main(String[] args)
{
int a=20,b=10,c=10;
try
{
int x=a/0;
System.out.println("x="+x);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
int y=a/(b+c);
System.out.println("y="+y);
}
}
try {
statements; // Statements that may
throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Multiple Catch Clauses
✓A try block can be followed by one or more catch
blocks.
✓Each catch block must contain a different exception
handler. So, if you have to perform different tasks at
the occurrence of different exceptions, use java
multi-catch block.
✓When an exception is thrown, each catch statement
is inspected in order, and the first one whose type
matches that of the exception is executed
✓After one catch statement executes, the others are
bypassed
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Arithmetic Exception occurs
rest of the code
Finally Block
• Java finally block is a block that is used to execute
important code such as closing connection, stream
etc.
• Java finally block is always executed whether
exception is handled or not.
• Java finally block follows try or catch block.
Java finally block
Finally Block Program
class trycatchfinally
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}

}
finally block is always executed
rest of the code...
Throw The Java throw keyword is
keyword used to explicitly throw an
exception.

We can throw either checked


or uncheked exception in java
by throw keyword. The throw
keyword is mainly used to
throw custom exception.
public class TestThrow1
{
static 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[])
{
validate(13);
System.out.println("rest of the code...");
}
}

Exception in thread main java.lang.ArithmeticException:not valid


throws
✓ If a method is capable of causing an exception that it does not
handle, it must specify this behavior so that callers of the
method can guard themselves against that exception
✓ type method-name parameter-list) throws exception-list
{
// body of method
}
✓ It is not applicable for Error or RuntimeException, or any
of their subclasses
class Example1
{
void method1() throws ArithmeticException
{
throw new ArithmeticException("Calculation error");
}
void method2() throws ArithmeticException
{
method1();
}
void method3()
{
try
{
method2();
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException handled");
}
}
public static void main(String args[])
{
Example1 obj=new Example1();
obj.method3();
System.out.println("End Of Program"); ArithmeticException handled
} End Of Program
}
User Defined Exception
✓Define a subclass of the Exception class.
✓The new subclass inherits all the methods of Exception and can
override them.
import java.lang.Exception;
import java.lang.*;
import java.io.DataInputStream;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class usedef
{
public static void main(String args[])
{
int age;
DataInputStream ds=new DataInputStream(System.in);
try
{
System.out.println("Enter the age (above 15 and below 25) :");
age=Integer.parseInt(ds.readLine());
if(age<15 || age> 25)
{
throw new MyException("Number not in range");
}
System.out.println(" the number is :" +age);
}
catch(MyException e)
{
System.out.println("Caught MyException"); Caught MyException
System.out.println(e.getMessage());
} Number not in range
catch(Exception e)
{
System.out.println(e);
}
}
}
Keyword Description

try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally.
It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed
by finally block later.

finally The "finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method.
It is always used with method signature.
No. final finally finalize

1) Final is used to apply Finally is used to place Finalize is used to


restrictions on class, important code, it will be perform clean up
:
method and variable. executed whether processing just
Final class can't be exception is handled or before object is
inherited, final method not. garbage collected.
can't be overridden, and
final variable value can't
be changed.
2) Final is a keyword. Finally is a block. Finalize is a
method.
Introduction to Thread
Multithreading Creation of Thread

Life cycle of Thread

Stopping and Blocking a Thread

Using Thread Methods

Thread Priority

Thread Synchronization

DeadLock
Introduction to Thread
• Process and Thread are two basic units of Java
program execution.
• Process: A process is a self contained execution
environment and it can be seen as a program or
application.
• Thread: It can be called lightweight process
• Thread requires less resources to create and exists in the
process
• Thread shares the process resources
Introduction to Thread
Multithreading

A program is divided
Multithreading in java is
into two or more
a process of executing
subprograms, which can
multiple processes
be implemented at the
simultaneously
same time in parallel.

Multiprocessing and
Java Multithreading is
multithreading, both are
mostly used in games,
used to achieve
animation etc.
multitasking.
Multithreading
Multithreading
ADVANTAGE:
▪ It doesn't block the user
▪ can perform many operations together so it
saves time.
▪ Threads are independent so it doesn't
affect other threads
During the lifetime of a
Life Cycle of thread, there are many
states it can enter.
a Thread
They include:

• Newborn state
• Runnable state
• Running state
• Blocked state
• Dead state
Life Cycle of a Thread
Life Cycle of a Thread
Newborn State:
▪ The thread is born and is said to be in newborn
state.
▪ The thread is not yet scheduled for running.
▪ At this state, we can do only one of the following:
• Schedule it for running using start() method.
• Kill it using stop() method.
Life Cycle of a Thread
Runnable State:
▪ The thread is ready for execution
▪ Waiting for the availability of the processor.
▪ The thread has joined the queue
Life Cycle of Running State:
a Thread • Thread is executing
• The processor has given
its time to the thread
for its execution.
• The thread runs until it
gives up control on its
own or taken over by
other threads.
Blocked State:
Life Cycle of • A thread is said to be blocked
a Thread • It is prevented to entering into the
runnable and the running state.
• This happens when the thread is
suspended, sleeping, or waiting in
order to satisfy certain requirements.
• A blocked thread is considered "not
runnable" but not dead and
therefore fully qualified to run again.
• This state is achieved when we Invoke
suspend() or sleep() or wait()
methods.
Dead State:
Life Cycle of • Every thread has a life cycle.
a Thread • A running thread ends its life
when it has completed executing
its run( ) method. It is a natural
death.
• A thread can be killed in born, or
in running, or even in "not
runnable" (blocked) condition.
• It is called premature death.
• This state is achieved when we
invoke stop() method or the
thread completes it execution.
Creating Thread

The run() and start()


Threads are are two inbuilt
implemented in the methods which helps
form of objects. to thread
implementation

The run() method is the


heart and soul of any The run() method can
thread be initiating with the
• – It makes up the entire help of start() method.
body of a thread
Creating By extending
Thread Thread Class

By implementing
Runnable
Interface
Main Thread created
Creating Thread thread is running...
1. By Extending Thread class

class MyThread extends Thread // Extending thread class


{
public void run() // run() method declared
{
System.out.println("thread is running...");
}
}
class ThreadMain
{
public static void main(String args[])
{
System.out.println("Main Thread created");
MyThread t=new MyThread(); //object initiated
t.start(); // run() method called through start()
}
}
Creating Thread
2. By implementing Runnable interface
▪ Define a class that implements Runnable
interface.
▪ The Runnable interface has only one method,
run(), that is to be defined in the method with the
code to be executed by the thread.
Main thread started
Creating Thread Main thread ended
thread is running...

2. By implementing Runnable interface


class MyThread implements Runnable // Implementing Runnable interface
{
public void run()
{
System.out.println("thread is running...");
}
}
class ThreadMain1
{
public static void main(String args[])
{
System.out.println("Main thread started"); // object initiated for class
MyThread t1=new MyThread(); // object initiated for thread
Thread t =new Thread(t1);
t.start();
System.out.println("Main thread ended");
}
Stopping and blocking
Stopping a thread:
• To stop a thread from running further, we may do
so by calling its stop() method.
• This causes a thread to stop immediately and
move it to its dead state.
• It forces the thread to stop abruptly before its
completion
• It causes premature death.
• To stop a thread we use the following syntax:
thread.stop();
Stopping and blocking
Blocking a Thread:
• A thread can also be temporarily suspended
or blocked from entering into the runnable
and subsequently running state,
1. sleep(t) // blocked for ‘t’ milliseconds
2. suspend() // blocked until resume() method is invoked
3. wait() // blocked until notify () is invoked
Thread Methods
• Thread is a class found in java.lang package.
Method Signature Description

String getName() Retrieves the name of running thread in the current


context in String format
This method will start a new thread of execution by
void start() calling run() method of Thread/runnable object.

void run() This method is the entry point of the thread. Execution of
thread starts from this method.
This method suspend the thread for mentioned time
void sleep(int sleeptime) duration in argument (sleeptime in ms)

By invoking this method the current thread pause its


void yield() execution temporarily and allow other threads to
execute.
This method used to queue up a thread in execution.
void join() Once called on thread, current thread will wait till calling
thread completes its execution

boolean isAlive() This method will check if thread is alive or dead


Thread Priority
• Each thread is assigned a priority, which
affects the order in which it is scheduled for
running.
• Java permits us to set the priority of a thread
using the setPriority() method as follows:

ThreadName.setPriority(int Number);
Thread Priority
• The intNumber is an integer value to which the
thread's priority is set. The Thread class defines
several priority constants:
1. public static int MIN_PRIORITY =1
2. public static int NORM_PRIORITY = 5
3. public static int MAX_PRIORITY = 10
• The default setting is NORM_PRIORITY. Most user-
level processes should use NORM_PRIORITY.
Generally threads use their own data and
Java methods provided inside their run() methods.

Synchronization
But if we wish to use data and methods outside
the thread’s run() method, they may compete
for the same resources and may lead to serious
problems.

Java enables us to overcome this problem using


a technique known as Synchronization.

For ex.: One thread may try to read a record


from a file while another is still writing to the
same file.
Java Synchronization
• When the method declared as synchronized,
Java creates a "monitor" and hands it over to
the thread that calls the method first time.

synchronized (lock-object)
{
.......... // code here is synchronized
}
Deadlock
• Deadlock describes a situation where two or
more threads are blocked forever, waiting for
each other.
• when two or more threads are waiting to gain
control on a resource.
For example, assume that the thread A must
access Method1 before it can release Method2, but
the thread B cannot release Method1 until it gets
holds of Method2.
Deadlock

You might also like