Unit 5-Exception Handling and Multithreading-1
Unit 5-Exception Handling and Multithreading-1
Errors
Types of errors
Compile time Error
Runtime Error
Compile Time Error
All syntax errors will be detected and displayed by
the java compiler and therefore these errors are
known as compile time errors.
Whenever the compiler displays an error, it will not
create the .class file.
Most common compile time errors
Missing semicolons
Missing brackets in classes and methods
Misspelling identifiers and keywords
Missing double quotes in strings
Use of undeclared variables
Use of = in place of == operator
Runtime Error
Sometimes, a program may compile successfully
creating the .class file but may not run properly.
Such programs may produce wrong results due to
wrong logic.
Most common run time errors
Contd…
Contd…
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a+b+c;
System.out.println("y="+y);
}
}
Common java exceptions
Exception Type Cause of Exception
ArithmaticException Caused by math errors such as
division by zero
ArrayIndexOutOfBoundsExceptio Caused by array indexes
n
ArrayStoreException Caused when a program tries to
store the wrong type of data in
an array
FileNotFoundException Caused by an attempt to access
a nonexistent file
IOException Caused by general I/O failure,
such as inability to read from a
file
Question
class TestFinally
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{ System.out.println("/ by 0"); }
finally
{ System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
Throwing our Own Exception
A programmer can create a new exception and
throw it explicitly.
These exceptions are known as user-defined
exceptions.
In order to throw user defined exceptions, throw
keyword is being used.
Syntax :
throw new Throwable_subclass;
Example :
throw new ArithmeticException();
Example class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestThrow
{
static void validate(int age)throws
InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
Contd…
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
throws keyword
The throws keyword is used in method declaration, in
order to explicitly specify the exceptions that a particular
method might throw.
When a method declaration has one or more exceptions
defined using throws clause then the method-call must
handle all the defined exceptions.
Syntax :
return_type method_name() throws
exception_class_name
{ //method code }
Example
import java.io.*;
class FileExThrow
{
void filecall() throws FileNotFoundException
{
FileInputStream fis = new
FileInputStream("D:/myfile.txt");
}
}
class Test_Throws
{
public static void main(String args[])
{
Contd… try
{
FileExThrow obj=new FileExThrow();
obj.filecall();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("a="+a);
}
}
Example
import java.io.*;
class ThrowsExample {
void mymethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("Exception Message1");
else
throw new ClassNotFoundException("Exception Message2");
}}
class TestThrows{
public static void main(String args[]){
try{
ThrowsExample obj=new ThrowsExample();
obj.mymethod(1);
}catch(Exception ex){
System.out.println(ex);
} }}
Multithread
programming
Threads
A thread is a light-weight smallest part of a process that
can run concurrently with the other parts(other threads) of
the same process.
Threads are independent because they all have separate
path of execution that’s the reason if an exception occurs
in one thread, it doesn’t affect the execution of other
threads.
All threads of a process share the common memory.
Thread in java
Single threaded program
Multithreading
Syntax:
class classname extends Thread
{ …………}
Example
class myThread extends Thread
{ ……….}
2. Implementing the run() method
The run() method has been inherited by the
subclass which we created previously.
We have to override this method in order to
implement the code to be executed by our thread.
Syntax :
public void run()
{
……//Thread code
}
3. Starting new Thread
Syntax:
classname objectname=new classname();
objectname.start();
Example :
MyThread t=new MyThread();
t.start();
Example class MultiT1 extends Thread{
public void run(){
for(int i=1;i<=3;i++)
{ System.out.println("Running Thread 1: "+i); }
System.out.println("exit from thread 1");
}
}
class MultiT2 extends Thread{
public void run(){
for(int i=1;i<=3;i++)
{ System.out.println("Running Thread 2: "+i);}
System.out.println("exit from thread 2");
contd…
contd…
}
}
class MyThread
{
public static void main(String args[]){
MultiT1 t1=new MultiT1();
t1.start();
MultiT2 t2=new MultiT2();
t2.start();
}
}
Output1 Output2 output3
Life cycle of a Thread
During life cycle of a thread, there are many states it can
enter.
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Thread Life cycle
Newborn state
When we create a thread object, the thread is born and is said to be
in newborn state.
The thread is not yet schedule for running.
We can do only one of the following things with it:
Schedule it for running using start() method
Kill it using stop() method
Ifwe attempt to use any other method at this stage, an exception will
be thrown.
Runnable state
The runnable state means that the thread is ready for execution
and is waiting for the availability of the processor.
The threads has joined the queue of threads that are waiting for
execution.
If we want a thread to release its control for another thread of
equal priority before its turn comes, we can do so by using yield()
method.
Running state
Running means that the processor has given its time to the
thread for its execution.
The thread runs until it releases control on its own or preempted
by a higher priority thread.
3. It has been told to wait until some event occurs. This is done using
wait() method. The thread can be scheduled to run again using the
notify() method.
Blocked state
A thread is said to be blocked when it is prevented from
entering into the runnable state and subsequently in running
state.
A blocked thread is considered not runnable but not dead.
A thread can blocked using following methods:
sleep() : blocked for specific time
suspend() : blocked until further orders
wait() : blocked until certain condition occurs
Dead state
t3.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(t1.getPriority()+1);
t1.setPriority(Thread.MIN_PRIORITY);
System.out.println("start of thread A");
t1.start();
System.out.println("start of thread B");
t2.start();
System.out.println("start of thread C");
t3.start();
}
}
Output
Synchronization
Synchronization in java is the capability to control the
access of multiple threads to any shared resource.
E.g. one thread may try to read a record from a file while
another is still writing to the same file. At this time we may
get strange result. To overcome this problem
synchronization is used.
Synchronized method
Synchronized method is used to lock an object for any shared
resource.
When a thread invokes a synchronized method, it automatically
acquires the lock for that object and releases it when the thread
completes its task.
When we declare a method synchronized, java created a monitor and
hands it over to the thread that calls the method first time. As long as
the thread holds monitor, no other thread can enter the synchronized
section of code. A monitor is a key and the thread that holds the key
can only open the lock.
E.g.
synchronized void update()
{ ……..
}
Synchronized block
Synchronized block can be used to perform synchronization on
any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want
to synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it
will work same as the synchronized method.
Syntax:
synchronized (object reference expression)
{
//code block
}
Implementing the Runnable
interface
Steps to implement Runnable interface: