UNIT-2
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
we will learn about Java exceptions, it's types, and the difference between checked and unchecked
exceptions.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.
Let's consider a scenario:
Hierarchy of Java Exception classes
The [Link] class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error.
Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
Example:
import [Link].*;
import [Link].*;
class class_checked {
public static void main(String[] args)throws FileNotFoundException
{
FileInputStream fns = null;
try {
fns = new FileInputStream("/desktop/pankaj/[Link]");
}
catch (FileNotFoundException e) {
[Link]("File does not exist");
}
}
}
Unchecked Exception
The classes that inherit the Runtime Exception are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
Examples:
mport [Link].*;
class class1 {
public static void main(String[] args)
{
int a[] = { 1, 2, 3, 4 };
[Link](a[5]);
}
}
Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
[Link] public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){
[Link](e);}
//rest code of the program [Link]("rest of the code...");
}
}
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.
However, we use multithreading than multiprocessing because threads use a shared memory area. They
don't allocate separate memory area so saves memory, and context-switching between the threads takes
less time than process.
Java Multithreading is mostly used in games, animation, etc. Advantages of Java Multithreading
It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
we can perform many operations together, so it saves time.
Threads are independent, so it doesn't affect other threads if an exception occurs in a singlethread.
What is Thread in java
A thread is a lightweight sub process, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
Next →← Prev
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states are:
New
Active
Blocked / Waiting
Timed Waiting
Terminated
class Multi extends Thread{
public void run(){ [Link]("thread is running...");
}
public static void main(String args[]){ Multi t1=new Multi();
[Link]();
}}
How to create a thread in java:-
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
o public void run(): is used to perform action for a thread.
o public void start(): starts the execution of the [Link] calls the run() method on the
thread.
o public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
o public void join(): waits for a thread to die.
Java Thread Example by extending Thread class
class class1 extends Thread
{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
class1 t1=new class1();
[Link]();
} }
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
[Link]();
} }
Java I/O:-
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The [Link] package contains all the classes
required for input and output operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it
is like a stream of water that continues to flow.
[Link]: standard output stream
[Link]: standard input stream
[Link]: standard error stream
import [Link];
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\[Link]"); [Link](65);
[Link](); [Link]("success...");
}catch(Exception e){[Link](e);}
Priority of a Thread in Java:-
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled. You can get and set the priority of a Thread. Thread class provides
methods and constants for working with the priorities of a Thread.
Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads.
MIN_PRIORITY: Specifies the minimum priority that a thread can have.
NORM_PRIORITY: Specifies the default priority that a thread is assigned.
MAX_PRIORITY: Specifies the maximum priority that a thread can have.
Thread Priority Setter and Getter Methods:- [Link]() Method: This method is
used to get the priority of a thread.
[Link]() Method: This method is used to set the priority of a thread, it accepts the
priority value and updates an existing priority with the given priority.
Example of Thread Priority in Java
public class TestThread {
public void printName() {
[Link]("Thread Name: " + [Link]().getName());
[Link]("Thread Priority: " +[Link]().getPriority());
}
public static void main(String a[]) {
TestThread thread = new TestThread();
[Link]();
}}
Synchronizing Threads
Synchronization thread in java
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
In the Multithreading concept, multiple threads try to access the shared resources at a time to produce
inconsistent results. The synchronization is necessary for reliable communication between threads.
Types of Synchronization:
Synchronization is classified into two types
Process Synchronization
Thread Synchronization
Process Synchronization:
The process is nothing but a program under execution. It runs independently
isolated from another process. The resources like memory and CPU time, etc.
are allocated to the process by the operation System.
Thread Synchronization:
Thread synchronization is two types, they are:
[Link] Exclusive:
A Mutex or Mutual Exclusive helps only one thread to access the shared resources. It won’t
allow the accessing of shared resources at a time. It can be achieved in the following ways.
Synchronized Method
Synchronized block
Static Synchronization
Inter process communication:-
Inter-thread communication in Java is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed.
Note: Inter-thread communication is also known as Cooperation in Java.
How Java multi-threading tackles this problem?
To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll(). All these
methods belong to object class as final so that all classes have them. They must be used within a
synchronized block only.
wait(): It tells the calling thread to give up the lock and go to sleep until some other thread enters
the same monitor and calls notify().
notify(): It wakes up one single thread called wait() on the same object. It should be noted that
calling notify() does not give up a lock on a resource.
notifyAll(): It wakes up all the threads called wait() on the same object.