Unit 04 Java
Unit 04 Java
In contrast, Java:
► Provides syntactic mechanisms to signal, detect and handle errors.
► Ensures a clean separation between the code executed in the absence of errors and the code to
handle various kinds of errors.
► Brings run-time error management into object-oriented programming.
An exception is an object that describes an exceptional condition (error) that has occurred when
executing a program.
Exception handling involves the following:
1) when an error occurs, an object (exception) representing this error is created and thrown in the
method that caused it
2) that method may choose to handle the exception itself or pass it on
3) either way, at some point, the exception is caught and processed
When and how it happens
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
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.
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.Java try block must be followed by either catch or finally block.
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Note: As displayed in the above example, the rest of the code is not executed.
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Java Nested try block
The try block within a try block is known as nested try block in java.
Syntax:
try
{
statement ;
try
{
statement ;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler.
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
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"); } }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Example:
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...");
}
}
Java throws keyword
The Java throws keyword is used to declare an exception.
It gives an information to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as NullPointerException, it is programmers fault
that he is not performing check up before the code being used.
System.out.println("normal flow...");
} }
Difference between throw and throws in Java
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple You can declare multiple exceptions
exceptions. e.g.
public void method()throws
IOException,SQLException.
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
A thread is a:
► Facility to allow multiple activities within a single process
► Referred as lightweight process
► A thread is a series of executed statements
► Each thread has its own program counter, stack and local variables
► A thread is a nested sequence of method calls
► Its shares memory, files and per-process state
Life cycle of a Thread
A thread can be in one of the five states
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Start()
Run method
Life cycle of a Thread
1. New
A newly created thread object instance on which the start() method has not yet been invoked(not yet
started execution) is in the new state.
2. Runnable A thread in New state enters the Runnable state when the start() method is invoked on
it.
There are 2 important points to note regarding the runnable state – ► When the thread enters the
runnable state after invoking the start() method, it is not necessary that the thread immediately
starts executing. A thread runs when the logic it holds in its method can be executed by the
processor. In case the thread logic needs any resource which is not available then the thread waits
for the resource to become available. ► A thread in runnable state may run for some time and then
get blocked or may enter the waiting or timed waiting states.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Output:thread is running...
Java Thread Example by implementing Runnable interface
Generally threads use their own data and methods provided inside their run() methods.
► 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.
► When the method declared as synchronized, Java creates a "monitor" and hands it over to the
thread that calls the method first time.
Syntax:
synchronized (lock-object)
{ .......... // code here is synchronized }
Rules for Synchronization
A thread must acquire the object lock associated with a shared resource, before it can enter the
shared resource.
The runtime system ensures that no other thread can enter a shared resource if another thread
already holds the object lock associated with the shared resource.
If a thread cannot immediately acquire the object lock, it is blocked, that is, it must wait for the lock
to become available.
When a thread exits a shared resource, the runtime system ensures that the object lock is also handed
over. If another thread is waiting for this object lock, it can proceed to acquire the lock in order to
access to the shared resource.
► The keyword ‘synchronized’ and the lock forms the basis for implementing synchronized
execution of code.
There are two different ways in which execution of code can be synchronized:
synchronized methods synchronized blocks
Synchronization Example
public class Synchronization implements Runnable {
{ bookticket (name, j);
int tickets = 3; }
static int i = 1, j = 2, k = 3; else
synchronized void bookticket (String name, int wantedtickets) {
{ bookticket (name, k);
if (wantedtickets <= tickets) }
{ }
System.out.println (wantedtickets + " booked to " + name); public static void main (String[]args)
tickets = tickets - wantedtickets; {
} Synchronization s = new Synchronization ();
else Thread t1 = new Thread (s);
{ Thread t2 = new Thread (s);
System.out.println ("No tickets to book"); Thread t3 = new Thread (s);
} t1.setName ("t1");
} t2.setName ("t2");
public void run () t3.setName ("t3");
{ t1.start ();
String name = Thread.currentThread ().getName (); t2.start ();
if (name.equals ("t1")) t3.start ();
{ }
bookticket (name, i); }
Deadlock
Synchronized keyword is used to make the class or method thread-safe which means only one
thread can have lock of synchronized method and use it, other threads have to wait till the lock
releases and anyone of them acquire that lock.
It is important to use if our program is running in multi-threaded environment where two or more
threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock.
Deadlock in java is a part of multithreading.
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by
another thread and second thread is waiting for an object lock that is acquire d by first thread.
Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
Inter –thread communication
When more than one thread uses a shared resource they need to synchronize with each other.
► While using a shared resource the threads need to communicate with each other, to get the
expected behavior of the application.
► Java provides some methods for the threads to communicate
Java provide benefits of avoiding thread pooling using inter-thread communication.
The wait(), notify(), and notifyAll() methods of Object class are used for this purpose.
These method are implemented as final methods in Object, so that all classes have them.
► All the three method can be called only from within a synchronized context
1. wait() : This method is used to make the particular Thread wait until it gets a notification. This
method pauses the current thread to the waiting room dynamically.
2. notify(): wakes up a thread that called wait() on same object.
3. notifyAll() : wakes up all the thread that called wait() on same object
Thank You