Professional Documents
Culture Documents
By.
G.Praveen Kumar
Assit.Prof , IT Dept.
SNIST.
G.Praveen ITDept-SNIST 1
UNIT III
G.Praveen ITDept-SNIST 2
Objective:- On the completion of the unit, a student should be able to:
G.Praveen ITDept-SNIST 3
Program Errors
G.Praveen ITDept-SNIST 4
1.Compile-time errors:
•These are syntactical errors found in
the code, due to which a program
fails to compile.
G.Praveen ITDept-SNIST 7
class RError{
public static void main(String args[])
{
int a=10,b=0;
System.out.println(“a/b: ”+(a/b));
}}
D:\>javac RError.java
D:\>java RError
Exception in thread "main" java.lang.ArithmeticException: / by zero
at RError.main(RError.java:4)
G.Praveen ITDept-SNIST 8
3.Logical errors:
•These errors depict flaws in the
logic of the program.
•The programmer might be using a
wrong formula or the design of the
program itself is wrong.
•Logical errors are not detected
either by the java compiler or JVM.
Cont…
G.Praveen ITDept-SNIST 9
•Logical errors means the logic of
the program is wrong and these are
identified after observing the
output.
G.Praveen ITDept-SNIST 10
class LError{
int sum(int a,int b){
return a-b;
}
public static void main(String args[]){
LError le=new LError();
System.out.println("Sum is: "+le.sum(20,10));
}
}
D:\>javac LError.java
D:\>java LError
Sum is: 10
G.Praveen ITDept-SNIST 11
What is an Exception?
• Dictionary Meaning: Exception is an
abnormal condition.”
• According to java language exception
is an event that disrupts the normal
flow of the program. It is an object
which is thrown at runtime
• An other words, an exception is a run-
time error.
G.Praveen ITDept-SNIST
Cont…
12
•Because of Exceptions the flow of
program execution is getting disturbed so
that program execution may continue (or)
may not be continued.
•Examples
• Division by zero
• Attempts to use an array index
out of bounds.
• Number input in wrong format
• Unable to write
G.Praveen ITDept-SNIST 13
Exception Handling
• Whenever an exception is occurred, handling
those exceptions called as “Exception
Handling”.
• Performing action in response to exception
• Examples
Exit program (abort)Ignore exception
Deal with exception and continue
• Print error message
• Request new data
• Retry actionG.Praveen ITDept-SNIST 14
Error:- Error is irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that
most applications should not try to handle.
Error defines problems that are not expected to be caught
under normal circumstances by our program.
For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code.
A developer can handle such conditions and take necessary
corrective actions.
Few examples –
DivideByZero exception
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
G.Praveen ITDept-SNIST 15
Benefits of Exception Handling
a. It allows us to fix the error.
b. It prevents program from automatically
terminating.
c. Separates Error-Handling Code from
Regular Code..
d. Conventional programming combines
error detection, reporting, handling
code with the regular code, leads to
confusion. G.Praveen ITDept-SNIST 16
Exception-Handling Fundamentals
G.Praveen ITDept-SNIST 20
An exception is an error which can be
handled. It means an exception happens,
the programmer can do something to
avoid any harm.
G.Praveen ITDept-SNIST 22
Unchecked Exceptions:- The exception which are
not checked by compiler and programmer handled or
not such type of exception are called unchecked
exception and programmer provide a safe execution of
the program and exit from the program.
G.Praveen ITDept-SNIST 23
Java Exception Class Hierarchy
G.Praveen ITDept-SNIST 24
Java Exception Class Hierarchy
Exception
G.Praveen ITDept-SNIST 25
Java Exception Handling Keywords:-
There are 5 keywords used in java exception handling.
1.try
2.catch
3.finally
4.throw
5.throws
G.Praveen ITDept-SNIST 26
Try Block:-The try block contains a block of program
statements with in which an exception might occur(risky
code) . A try block is always followed by a catch block,
which handles the exception that occurs in associated try
block. A try block must followed by a Catch block or
Finally block or both.
Syntax of try block
Try
{
//statements that may cause an exception
}
G.Praveen ITDept-SNIST 27
Catch Block:- catch block must be associated with a
try block. The corresponding catch block executes if
an exception of a particular type occurs within the try
block. For example if an arithmetic exception occurs in
try block then the statements enclosed in catch block
for arithmetic exception executes.
Syntax of try catch in java
Try
{ //statements that may cause an exception }
catch (exception(type) e(object))
{
//error handling code
}
G.Praveen ITDept-SNIST 28
public class Pro1{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code1...");
}
}
OUTPUT:-
C:\praveen\UNTI-4>java Pro1
java.lang.ArithmeticException: / by zero
rest of the code1...
G.Praveen ITDept-SNIST 29
Internal working of java try-catch block
G.Praveen ITDept-SNIST 30
The JVM firstly checks whether the exception is
handled or not. If exception is not handled, JVM
provides a default exception handler that performs the
following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the
exception occurred).
Causes the program to terminate.
But if exception is handled by the application
programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
G.Praveen ITDept-SNIST 31
Multiple Catch Blocks:-If user have to perform different tasks in a single
code at the occurrence of different Exceptions these exception s are handled
by use java multi catch block.
A try block can be followed by multiple catch blocks. After one catch
statement executes, the others are bypassed, and execution continues
after the try/catch block.
The syntax for multiple catch blocks looks like the following
Syntax:-
try {
// Protected code
}
catch(ExceptionType1 e1)
{
// Catch block
}catch(ExceptionType2 e2)
{
// Catch block }catch(ExceptionType3 e3)
{
// Catch block G.Praveen ITDept-SNIST 32
From The above syntax three catch blocks, you can have any
number of them after a single try. If an exception occurs in the
protected code, the exception is thrown to the first catch block in
the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes
down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which
case the current method stops execution and the exception is
thrown down to the previous method on the call stack.
G.Praveen ITDept-SNIST 33
class MCatch {
public static void main(String args[]) { OUTPUT:-
1) C:\praveen\UNIT-4>java MCatch
try {
a=0
int a = args.length; Divide by 0: java.lang.ArithmeticExceptio
System.out.println("a = " + a); zero
int b = 42 / a; After try/catch blocks.
int c[] = { 1 }; EXCEPTION FREE ZONE
c[42] = 99; 2) C:\praveen\UNIT-4>java MCatch 10
} a=1
catch(ArithmeticException e) Array index oob:
{ java.lang.ArrayIndexOutOfBoundsExcep
After try/catch blocks.
System.out.println("Divide by 0: " + e);
EXCEPTION FREE ZONE
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
System.out.println("EXCEPTION FREE ZONE ");
}}
G.Praveen ITDept-SNIST 34
class MCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(Exception e){System.out.println("common task completed");}
/*catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}*/
System.out.println("After try/catch blocks.");
System.out.println("EXCEPTION FREE ZONE ");
}}
C:\praveen\UNIT-4>java M
a=0
common task completed
After try/catch blocks.
EXCEPTION FREE ZONE
G.Praveen ITDept-SNIST 35
Java Nested try block:-The try block within a try block is known
as nested try block in java
Each time a try statement is entered, the context of that exception is
pushed on the stack.
If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
This continues until one of the catch statements succeeds, or until
all of the nested try statements are exhausted.
If no catch statement matches, then the Java run-time system will
handle the exception.
NOTE:-Why use nested try block
Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In
such cases, exception handlers have to be nested.
G.Praveen ITDept-SNIST 36
try {
statement 1;
statement 2; //try-catch block inside another try block
try
{
statement 3;
statement 4; //try-catch block inside nested try block
try
{
statement 5;
statement 6;
} catch(Exception e2){
//Exception Message
}
} catch(Exception e1) {
//Exception Message
} } //Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
G.Praveen ITDept-SNIST 37
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
G.Praveen ITDept-SNIST 38
class NTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
if(a==1) a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}}}
G.Praveen ITDept-SNIST 39
OUTPUT:-
C:\praveen\UNIT-4>java NTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\praveen\UNIT-4>java NTry 1
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\praveen\UNIT-4>java NTry 2
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\praveen\UNIT-4>java NTry 23
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\praveen\UNIT-4>
G.Praveen ITDept-SNIST 40
finally block:-finally block is a block that is used to execute
significant code such as closing connection, stream etc.
G.Praveen ITDept-SNIST 41
Finally block is use to put "cleanup" code such as closing a file, closing
connection etc.
executed");}
System.out.println("rest of the code...");
}
}
G.Praveen ITDept-SNIST 42
2. finally example where exception occurs and handled.
public class Finally2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
G.Praveen ITDept-SNIST 43
class ThrowDemo { // Demonstrate throw.
static void demoproc()
{
try {
int data=50/10;
throw new NullPointerException(); OUTPUT:-
} C:\praveen\UNIT-4>java ThrowDemo
Caught inside demoproc.
catch(ArithmeticException e) Recaught: java.lang.NullPointerException
{
System.out.println(e);
}
catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}}
public static void main(String args[]) {
try {
demoproc();
}catch(NullPointerException e) {
System.out.println("Recaught: G.Praveen
" + e); ITDept-SNIST 44
throw keyword:-The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception(user-defined exception).
Program can also throw an exception explicitly, using the throw statement.
The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
There are two ways you can obtain a Throwable object:
using a parameter into a catch clause, or
creating one with the new operator.
The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
It finds the catch which is suitable, if it does find a match, control is transferred
to that statement.
If not, then the next enclosing try statement is inspected, and so on.
If no matching catch is found, then the default exception handler halts the
program and prints the stack trace.
G.Praveen ITDept-SNIST 45
throws keyword:-throws is a keyword in java language which is used to throw
the exception which is raised in the called method to it's calling method throws
keyword always followed by method signature.
G.Praveen ITDept-SNIST 46
Difference between throw and throws in Java:- There are many differences
between throw and throws keywords
throw throws
Java throw keyword is used to Java throws keyword is used to declare
explicitly throw an exception. an exception.
Checked exception cannot be Checked exception can be propagated
propagated using throw only. with throws.
Throw is followed by an instance. Throws is followed by class.
Eg:-void m(){ void m()throws ArithmeticException{
throw new ArithmeticException("sorry"); throw new ArithmeticException("sorry");
}
}
Throw is used within the method. Throws is used with the method
signature.
We cannot throw multiple exceptions. We can declare multiple exceptions
e.g.
public void method()throws
G.Praveen ITDept-SNIST 47
IOException,SQLException.
Java’s Built-in Exceptions:-
Inside java.lang package, Java defines several exception classes.
These are called unchecked exceptions because the compiler does not
check to see if a method handles or throws these exceptions.
G.Praveen ITDept-SNIST 48
Java’s Unchecked RuntimeException Subclasses
G.Praveen ITDept-SNIST 49
G.Praveen ITDept-SNIST 50
Java’s Checked Exceptions Defined in java.lang
G.Praveen ITDept-SNIST 51
Creating Your Own Exception Subclasses
To create own exception types to handle situations specific to your applications.
The Exception class does not define any methods of its own. It does, of
course, inherit those methods provided by Throwable.
Thus, all exceptions, including those that you create, have the methods
defined by Throwable available to them.
You may also wish to override one or more of these methods in exception
classes that you create.
G.Praveen ITDept-SNIST 52
Every user defined Exception last word must be Exception since every
exception is a class.
E.g., AgeException
MarksOutOfBoundsException
G.Praveen ITDept-SNIST 53
class MyException extends Exception { // This program creates a custom exception type.
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20); Called compute(1)
}
Normal exit
catch (MyException e) {
System.out.println("Caught " + e); Called compute(20)
} Caught MyException[20]
}
}
G.Praveen ITDept-SNIST 54
Custom Exception in Java:-If any exception is design by the user known as user
defined or Custom Exception. Custom Exception is created by user.
G.Praveen ITDept-SNIST 55
Single Tasking :- A task means doing some calculation, processing, etc.
In single tasking environment, only one task is given to processor at a time.
This means we are wasting a lot of processor time and processor has to sit idle without
any job for a long time.
G.Praveen ITDept-SNIST 56
Multi Tasking :-multi tasking environment perform several tasks are given
to processor at a time.
most of the processor time is getting engaged and it is not sitting idle.
Uses:
To use the processor time in a better way.
To achieve good performance.
To make processor not to sit idle for long time.
G.Praveen ITDept-SNIST 57
Multitasking:- Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU. Multitasking can
be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
G.Praveen ITDept-SNIST 59
Process-based vs. Thread-based
1. A process is a program that is 1. A thread is a separate path of
executing. execution.
G.Praveen ITDept-SNIST 60
Thread Life cycle (Thread States):- The life cycle of the thread in java is controlled
by JVM. Starting from the birth of a thread, till its death, a thread exists in different
states which are collectively called “Thread Life Cycle”.
T
)
ar t( Schedular dispatch
st
MAIN MEMORY
G.Praveen ITDept-SNIST 61
1. New State:-If any new thread class is created that represent new state of
a thread, In new state thread is created and about to enter into main
memory.
No memory is available if the thread is in new state.
2. Ready (Runnable) State: A thread start its life from Runnable state. A
thread first enters Runnable state after the invoking of start() method but a
thread can return to this state after either running, waiting, sleeping or
coming back from blocked state also. On this state a thread is waiting
for a turn on the processor.
G.Praveen ITDept-SNIST 62
4. Blocked State: A thread can enter in this state because of waiting the
resources that are hold by another thread.
5. Dead State: A thread can be considered dead when its run() method
completes. If any thread comes on this state that means it cannot ever run
again. no memory is available for the thread if its comes to dead state.
G.Praveen ITDept-SNIST 63
Thread Life Cycle (Contd..)
A thread will be born when it is created using Thread class as:
Thread obj=new Thread();
A thread goes into runnable state when start() method is applied on it.
That is void start() method is used to call the public void run() method.
From runnable state, a thread may get into not-runnable state, when sleep()
or wait() or suspend() methods act on it.
notify() and resume() methods are used to restart waiting and suspended
threads respectively.
yield() method causes the currently executing thread object to temporarily
pause and allow other threads to execute.
Thread Death class will be invoked whenever the stop() method is called.
G.Praveen ITDept-SNIST 64
Single Thread System Vs. Multi Thread System
G.Praveen ITDept-SNIST 65
Thread Creation:- There are two ways to create a Thread:
G.Praveen ITDept-SNIST 66
Thread Class Constructors
1. Thread():- Allocates a new Thread Object.
E.g., Thread t=new Thread();
G.Praveen ITDept-SNIST 67
5. Thread(ThreadGroup group, String name):- Allocates a new Thread object.
Where group is the thread group, target is the object whose run method is called.
G.Praveen ITDept-SNIST 68
To create a Thread need to override run( ) method available in Thread
class. This method provides an entry point for the thread Following is a
simple syntax of run() method
Syntax:- public void run( )
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
System.out.println("WELCOME IT-DEPT JAVA THREAD...");
}
public static void main(String args[]){ OUTPUT:-
Multi t1=new Multi(); D:\UNIT-4>javac Multi.java
t1.start();
} D:\UNIT-4>java Multi
} thread is running...
WELCOME IT-DEPT JAVA THREAD
G.Praveen ITDept-SNIST 69
2. By implementing Runnable interface:- By using this interface
we will implement a thread by create Thread object explicitely .
EG:- class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
If there are not extending the Thread class, The class object would not be
treated as a thread object. So you need to explicitly create Thread class
object. We are passing the object of your class that implements Runnable
so that your class run() method may execute.
G.Praveen ITDept-SNIST
Thread Class Methods
Method Description
1.public void run() is used to perform action for a thread.
2.public void start() starts the execution of the thread.JVM calls the
run() method on the thread.
3.public void sleep(long Causes the currently executing thread to sleep
miliseconds)
4.public void join() waits for a thread to die.
5.public void join(long waits for a thread to die for the specified
miliseconds): milliseconds.
6.public int getPriority() returns the priority of the thread.
7.public int setPriority(int changes the priority of the thread.
priority)
8.public String getName() returns the name of the thread.
9.public void changes the name of the thread.
setName(String name)
G.Praveen ITDept-SNIST 71
Method Description
10. public Thread returns the reference of currently executing thread.
currentThread():
11. public int getId() returns the id of the thread.
12. public Thread.State returns the state of the thread.
getState()
13. public boolean isAlive() tests if the thread is alive.
14. public void yield() causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15. public void suspend() is used to suspend the thread(depricated).
16. public void resume() is used to resume the suspended thread(depricated).
17. public void stop() is used to stop the thread(depricated).
18. public boolean isDaemon() tests if the thread is a daemon thread.
19. public void interrupt() interrupts the thread.
20. public static boolean tests if the current thread has been interrupted.
interrupted()
G.Praveen ITDept-SNIST 72
Thread Class Methods:-
1. public static void sleep(long millis, int nanos) throws InterruptedException
Causes the currently executing thread to sleep for the specified
number of milliseconds plus the specified number of
nanoseconds.
G.Praveen ITDept-SNIST 73
NOTE 1: The value of new Priority must be within the range
MIN_PRIORITY and MAX_PRIORITY (1 and 10), for default priority,
specify NORM_PRIORITY, which is currently 5. These priorities are defined
as final variables within Thread.
NOTE 2:A thread’s priority is used to decide when to switch from one
running thread to the next. This is called a context switch.
A thread can voluntarily relinquish control.
A thread can be preempted by a higher-priority thread.
G.Praveen ITDept-SNIST 74
main Thread
G.Praveen ITDept-SNIST 75
class One extends Thread{
public void run(){
for(int i=0;i<5;i++){
System.out.println("THread-1 value: "+i);
}}}
class Two extends Thread{
public void run(){
for(int j=10;j>4;j--){
System.out.println("Thread-2 value"+j);
} }}
class Multi2{
public static void main(String sree[]){
One o=new One(); C:\praveen\UNIT-4>java Multi2
o.start(); THread-1 value: 0
Two t=new Two(); THread-1 value: 1
t.start();
}} THread-1 value: 2
THread-1 value: 3
THread-1 value: 4
Thread-2 value10
Thread-2 value9
Thread-2 value8
Thread-2 value7
Thread-2 value6
Thread-2 value5
G.Praveen ITDept-SNIST 76
Difference between “extends Thread” and “implements Runnable” :
2. But when we write extends Thread, there is no scope to extend another class, as
multiple inheritance is not supported in java.
3. If we write implements Runnable, then still there is scope to extend another class.
4.This is definitely advantageous when the programmer wants to use threads and also
wants to access the features of another class.
G.Praveen ITDept-SNIST 77
//Program to display the name of the threads
class Demo extends Thread{
public void run(){
System.out.println(getName());
}}
class Multi4{
public static void main(String args[]){
Thread t=Thread.currentThread();System.out.println("CURRENT Main Thread is:
"+t.getName());
Demo obj1=new Demo();
Demo obj2=new Demo();
Demo obj3=new Demo();
obj1.start();
obj2.start();
obj3.start(); C:\praveen\UNIT-4>java Multi4
} CURRENT Main Thread is: main
} Thread-0
Thread-2
Thread-1
G.Praveen ITDept-SNIST 78
Thread Scheduler:- Thread scheduler in java is the part of the JVM that
decides which thread should run.
The scheduler maintains a pool of threads. When Java thread is started
calling start() method, it joins the pool of waiting threads. For deciding
processor allocation for each waiting thread, the scheduler takes many
aspects into consideration.
1.Priority of thread
2. Waiting time of thread
3. Nature of thread
G.Praveen ITDept-SNIST 79
Java Thread Scheduler Conti…
JVM starts executing a Java program, it creates a few threads for
the execution.
1. main is a method for us, but main is a thread for JVM. The
execution starts with main thread.
2. Garbage collector is a daemon thread that comes into action
before every thread.
3. Event Dispatcher is a thread which will take care of events
raised by the components like click of a button etc.
4. There is one more, Timer thread, which maintains the time for
methods like sleep() etc.
G.Praveen ITDept-SNIST 80
A thread is started with start() method, the Java thread joins the pool of
waiting threads.
It does not mean the scheduler should give the processor time
immediately.
it is guaranteed of getting processor time, but at what time depends on
the decision of the scheduler managed by the OS.
When a thread joins, the scheduler is executed by the OS and makes a
table of threads' sequence to allocate processor time.
When a sleep() method is called, the thread is removed from the active
pool, then again the scheduler is executed to make the table as there
comes imbalance in the waiting threads.
And executed again when the thread joins the pool when
the sleep() time is over. the scheduler executes a number of times when
a thread joins, yields, stops or leaves (when blocked or dies) the pool.
G.Praveen ITDept-SNIST 81
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
TestMultiPriority1 m3=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start(); D:\UNIT-4>java TestMultiPriority1
m3.start(); running thread name is:Thread-1
} running thread name is:Thread-0
} running thread name is:Thread-2
running thread priority is:1
running thread priority is:10
running thread priority is:5
G.Praveen ITDept-SNIST
D:\UNIT-4>
82
join():-
Often we want the main thread to finish last.
It does not happen automatically.
We uses join( ) to ensure that the main thread is the last to stop.
G.Praveen ITDept-SNIST 83
Creates Thread t1
Main thread
Calls t1.join()
Main thread
resumes
G.Praveen ITDept-SNIST
Daemon Thread:-Daemon thread in java is a service provider thread it
provides services to the user thread. Its life depend on the compassion of user
threads i.e. when all the user threads dies, JVM terminates this thread
automatically.
They can not prevent the JVM from exiting when all the user threads finish
their execution.
JVM terminates itself when all user threads finish their execution
If JVM finds running daemon thread, it terminates the thread and after that
shutdown itself. JVM does not care whether Daemon thread is running or not.
G.Praveen ITDept-SNIST 85
Methods:-
1.void setDaemon(boolean status): This method is used to mark the current
thread as daemon thread or user thread
Syntax:
public final void setDaemon(boolean on)
parameters: on : if true, marks this thread as a daemon thread.
exceptions: IllegalThreadStateException: if only this thread is active.
SecurityException: if the current thread cannot modify this thread.
G.Praveen ITDept-SNIST 86
public class TestDaemon extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemon t1=new TestDaemon();//creating thread
TestDaemon t2=new TestDaemon();
TestDaemon t3=new TestDaemon();
G.Praveen ITDept-SNIST 87
USER DEFINED EXCEPTIONS:-
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
} }
class TestCustomException1{