0% found this document useful (0 votes)
2 views45 pages

CH 3

Chapter 3 covers Exception Handling and Multithreading in Java, detailing types of errors and exceptions, including compile-time and run-time errors, as well as exception handling mechanisms using try, catch, throw, throws, and finally statements. It also discusses multithreaded programming, explaining thread creation, life cycle, and synchronization to manage shared resources among threads. The chapter emphasizes the importance of error management and the ability to run multiple threads concurrently in Java applications.

Uploaded by

hsg8656
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)
2 views45 pages

CH 3

Chapter 3 covers Exception Handling and Multithreading in Java, detailing types of errors and exceptions, including compile-time and run-time errors, as well as exception handling mechanisms using try, catch, throw, throws, and finally statements. It also discusses multithreaded programming, explaining thread creation, life cycle, and synchronization to manage shared resources among threads. The chapter emphasizes the importance of error management and the ability to run multiple threads concurrently in Java applications.

Uploaded by

hsg8656
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/ 45

Ch 3 :Exception Handling and Multithreading

Topics Covered:
1. Errors and Exception: Types of errors and exceptions, try and catch
statements, throws and finally statements, built-in exceptions, throwing our
own exception.
2 Multithreaded programming: creating a thread: By extending to thread class
and by implementing runnable Interface, Life cycle of thread: Thread
methods, thread exceptions, thread priority and methods, synchronization.
Total Marks – Min 12 marks.
Topic 1 : Errors and Exception
Exceptions:
-An exception is a condition that is caused by a run-time error in the program.

Errors:
-Errors are the mistakes that can makes program to go wrong.
-Error may produce an incorrect output or may terminate the execution of the program or even may cause the system
to crash.
-So it is important to detect & manage all error condition in the program. So that programs will not terminate or crash
during execution.
Topic 1 : Types of errors
Error are classified in two types as follows :
1) Compile Time Error
2) Run Time Error
Topic 1 : Run Time Error
Run Time Error :
-Sometimes, a program may compile successfully, creating .class file , but may not run properly such programs may
terminate due to errors such as file not found or memory problem.
-The error which are generated while program is running are known as Run Time Errors.
Examples of Run Time Error:-
-Dividing an integer by zero.
-Accessing an element that is out of the bounds of an array
-Trying to store a value into an 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 in a valid range or value for a method
-Attempting to use a negative size for an array
Topic 1 : Compile Time Error
Compile Time Error :
-All the syntax errors that are detected & displayed by the java compiler are known as Compile Time Errors.
-Whenever compiler displays this syntax errors, it will not create .class file.
Examples of Compile Time Error:-
-Missing semicolons
-Missing (or mismatch of) brackets in classes and methods
-Misspelling of identifiers and keywords
-Missing double quotes in strings-
-Use of undeclared variables
-Incompatible types in assignments / initialization
-Bad references to objects
Topic 1 : Types of exceptions
-Checked Exception
The exception that can be predicted by the programmer at the compile time. Example : File that need to be opened is not
found. These type of exceptions must be checked at compile time.
-Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile
time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are
checked at runtime.
Topic 1 : Exceptions Handling
Exception Handling Mechanism performs

-Find the problem (Hit the exception).


-Inform that an error has occurred (Throw the exception)
-Receive the error information (Catch the exception)
-Take corrective actions (Handle the exception)
Topic 1 : Exceptions Handling
Exception Handling clause

-In java, exception handling is done using five keywords,


try
catch
throw
throws
finally
Topic 1 : try and catch statements
-A block of a code that is likely causes an error condition & throw an exception should be enclosed in a try block.
-An exception thrown by the try block should be caught & this statement enclosed under the catch box.
-The try block contains one or more statement, which generates an exception.
-If the one statement generates an exception then the remaining statements are skipped & execution jumps to
the catch block.
-Every try block must be followed by at least one catch statement, otherwise compilation error occurs.
-The catch statement is passed a single parameter which is reference to the exception object thrown by the try
block.
-If the catch parameter matches with the type of exception object, then the exception is caught and the
statements in the catch block will be executed, otherwise it terminates the execution of the program.
Topic 1 : try and catch statements
Syntax:-
try
{
//Block of code to monitor for error
}
catch(Exception e)
{
//Exception handling for exception
}
Topic 1 : try and catch statements
try-catch:
Topic 1 : try and catch statements
Nested try-catch:
Topic 1 : throws
 throws

-If the method is capable of causing an exception that does not handled, it must be specify this behavior to the
callers of the method so that they can guard themselves against that exception.
-This can be done by including throws clause in the method declaration.
-throws clause can throw a number of exceptions.
-General form of the method declaration that includes throws clause:
data_type method_name(parameters) throws Exceptionlist
Topic 1 : throws
 throws : single exception
Topic 1 : throws
 throws: multiple exception
Topic 1 : throw
 throw:

-All the system defined exception is thrown automatically, but the user defined exception must be thrown
explicitly using throw clause.
-throw clause is used to explicitly throw a user defined exception.
-When throw statement is executed, the flow of execution stops immediately after the throw statement & any
subsequent statements are not executed.
Topic 1 : throw
 throw:
Topic 1 : finally
 finally:

-Because of execution of try block the execution gets break off. Due to this some important code (which comes after
throwing off an exception) may not get executed.
-The finally block provides the assurance of execution of some important code that must be executed after the try block.
- Eventhough there is any exception in the try block the statements assured by finally block are sure to execute.
- These statements are sometimes called as clean up code.
- Syntax:
finally
{

}
Topic 1 : finally
 finally:
Topic 1 : built-in exceptions
Topic 1 : throwing our own exception
User defined exception:-
-It is an exception which created by defining a subclass by inheriting the built in exception class and then by throwing
an object of user defined exception class from try-catch block.
-Syntax for defining user define exception:-
class classname extends Exception
{
//body;
}
Topic 1 : throwing our own exception
Topic 2 : Multithreaded programming
Multithreading
-Multitasking is allowing the user to handle multiple tasks together.
-In java we can write the program that performs multitasking using the multithreading concept.
-Thus java allows to have multiple control flows in a single program by means of multithreading.
Topic 2 : Multithreaded programming
Thread
-Java enables us to use multiple flows of control in developing programs, where each flow of control is a separate tiny
program known as thread that runs in parallel to other.
-Thread is similar to a program that has a single flow of control.
-It has beginning, a body & an end and executes command sequentially.
-Since threads in java are subprograms of main application program & share the same memory space. So they are
known as lightweight threads or process.
-As that the threads running in parallel does not really mean that they actually run at the same time. Since all the
threads are running on a single processor, flow of execution is shared between the threads. So java handles the
switching of control between the threads in such a way that they are running concurrently.
Topic 2 : Life cycle of thread
Thread Life Cycle
Topic 2 : Life cycle of thread
I] Newborn State:-
-When we create a thread object, our thread is born & is said to the newborn state.
-Syntax:-
Thread t = new Thread();
In newborn state, thread is not yet scheduled; once it is scheduled it can move into the runnable state.
Topic 2 : Life cycle of thread
II] Runnable State(Ready to run):-
◦ Runnable state means that thread is ready for execution & is waiting for availability of the process.
◦ Syntax:-

t.start();
◦ yield() :-

If we want thread to give up the control to another thread of equal priority before its turns come, we
can do so by using yield method.
Topic 2 : Life cycle of thread
III] Running State :-
◦ It means that the processor has given it time to the thread for its execution.
◦ Syntax:-

t.run();
◦ Thread run until it gives up controls on its own or it is preempted by higher priority thread.
◦ Running thread may give up its control in one of the following situation:-
Topic 2 : Life cycle of thread
◦ suspend():-
It is use to suspend a thread for some time due to certain reason but do not want to kill it. A suspended thread can be
revived by using resume().
Topic 2 : Life cycle of thread
sleep():-
It is use to make the thread to sleep for specific time period (time in milliseconds). This means that thread is
out of queue during this time period. The thread reenters into runnable state as soon as time period is elapsed.
Topic 2 : Life cycle of thread
◦ wait():-
It is use to tell the thread to wait until some event occurs. The thread can be scheduled to run again using
notify() method.
Topic 2 : Life cycle of thread
IV] Blocked State:-
◦ A thread is said to be a block when it is prevented from entering into runnable & running.
◦ Thread can enter in a blocked state because of waiting for the resources that are hold by another thread.
◦ To come out of the block state
◦ In case of suspend() method it use resume() method.
◦ In case of sleep() method it use t’sec() method.
◦ In case of wait() method it use notify() method.
Topic 2 : Life cycle of thread
V] Dead State:-
◦ Every thread has life cycle. Running thread ends its life when it has completed executing its run method.
◦ Syntax:-

t.stop();
Topic 2 : creating a thread: By extending to
thread class and by implementing runnable
Interface
In java we can implement the thread program using two approaches-
1) Using Thread class
2) Using runnable interface
Topic 2 : creating a thread: By extending to
thread class
Declare class as extending Thread class
Syntax
Class class-name extends Thread
{
//body
}
Implement run() method that thread will be execute
Syntax
public void run()
{
//body
}
Topic 2 : creating a thread: By extending to
thread class
Create thread object in main program
Syntax
Class-name Threadobj=new class-name();

Call start() method


Syntax
Threadobj.start();
Topic 2 : creating a thread: By extending to
thread class
WAP to create two threads such that one will print odd Number and other thread will print even Number between 1 to 20
Nos.
Topic 2 : creating a thread: By
implementing runnable Interface
Declare the class as implementing Runnable interface

Syntax
Class class-name implements Runnable

{
}
Implement run() method

Syntax
Public void run()
{
}
Topic 2 : creating a thread: By
implementing runnable Interface
Create a thread object

Syntax
Class-name obj=new class-name();

Instantenous from runnable interface

Syntax
Thread threadobj=new Thread(obj);

Call start() method

threadobj.start();
Topic 2 : creating a thread: By
implementing runnable Interface
Topic 2 : thread exceptions
thread exceptions:
-When we use sleep() method during thread programming, then we must enclose this sleep() method within a try block
because sleep method throws an exception.
-Java will throw IllegalThreadStateException whenever we attempt to call a method which cannot be handled by
therad.
Topic 2 : thread priority and methods
Thread priority and methods:
-Priority determines that how thread should be treated with respect to other.
-Priority is considered by thread scheduler who decides which ready thread should execute
-Every thread in java has equal priority i.e. default=5. So they share processor on basis of FCFS.
-Java permits us to set priority of a thread using setPriority() method.
Syntax:-
Threadname.setPriority(int no.);
Where int no. is an integer value to which thread priority is to be set.
-Thread class defines several priority constants
◦ MIN_PRIORITY = 1
◦ NORM_PRORITY = 5
◦ MAX _PRIORITY =10

The getPriority() method returns the priority of the thread.


Topic 2 : thread priority and methods
Topic 2 : synchronization
Synchronization
-When two or more threads need to access to a shared resource i.e. either of method or an object then they
need some way to ensure that the shared resource will be used by only one thread at a time. The process by
which it is achieved is known as Synchronization.
-When method is mark as synchronized java creates some monitor object for the class. i.e. monitor is used as
mutually exclusive lock called as “mutex”.
-When the first time thread calls the synchronized method, java gives the monitor object to that thread. As long
as the thread holds the monitor object, no other thread can enter in the synchronized session of the code.
-When thread completes its work of using synchronized() method, It will hand over the monitor to the next
thread to use the same resource
Topic 2 : synchronization

You might also like