CH 3
CH 3
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
-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();
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();
Syntax
Thread threadobj=new Thread(obj);
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